<template>
  <div class="facebook-container">
    <!-- 使用封装的顶部导航组件 -->
    <MainHeader />
    
    <!-- 主要内容区 -->
    <div class="main-container">
      <!-- 使用封装的侧边菜单组件 -->
      <SideMenu />
      
      <!-- 右侧内容区 -->
      <div class="content">
        <!-- 搜索区域 -->
        <div class="search-container">
          <div class="search-title">{{ t('search') }}</div>
          
          <!-- 搜索输入区 -->
          <div class="search-box-container">
            <el-input
              v-model="state.queryParams.name"
              :placeholder="t('facebook.search.placeholder')"
              clearable
              class="search-input"
              @clear="resetNameSearch"
              @input="handleNameInputChange"
              prefix-icon="el-icon-search"
            >
            </el-input>
          </div>
        </div>
        
        <!-- 主内容区域 - 左侧筛选器 + 右侧卡片列表 -->
        <div class="facebook-main">
          <!-- 左侧筛选器，添加固定效果 -->
          <div class="filter-sidebar-container">
            <div class="filter-sidebar">
              <!-- 添加重置按钮 -->
              <div class="reset-filter-container">
                <el-button @click="resetAllFilters(true)" class="reset-filter-btn">
                  {{ t('facebook.filter.reset') }}
                </el-button>
              </div>
              
              <!-- 性别筛选 -->
              <div class="filter-group" :class="{ expanded: state.expanded.gender }">
                <div class="filter-header" @click="toggleFilter('gender')">
                  <span>{{ t('facebook.filter.gender') }}</span>
                  <i :class="['el-icon', state.expanded.gender ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="state.expanded.gender" class="filter-content">
                  <!-- 使用复选框，第一个为全选 -->
                    <el-checkbox :model-value="state.checkAll.gender" @change="handleGenderCheckAllChange">{{ t('facebook.filter.all') }}</el-checkbox>
                  <el-divider></el-divider>
                    <el-checkbox-group v-model="state.filters.genders" @change="handleGenderChange">
                    <div v-for="gender in [{'value': 'M', 'label': t('facebook.gender.male')}, {'value': 'F', 'label': t('facebook.gender.female')}]" :key="gender.value">
                        <el-checkbox :label="gender.value">
                          {{ gender.label }}
                        </el-checkbox>
                      </div>
                    </el-checkbox-group>
                </div>
              </div>
              
              <!-- 当前所在地筛选 -->
              <div class="filter-group" :class="{ expanded: state.expanded.currentLocation }">
                <div class="filter-header" @click="toggleFilter('currentLocation')">
                  <span>{{ t('facebook.current.location') }}</span>
                  <i :class="['el-icon', state.expanded.currentLocation ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="state.expanded.currentLocation" class="filter-content">
                  <div class="filter-search" :class="{ 'is-loading': esSearchLoading.currentLocation }">
                    <el-input v-model="currentLocationSearch" @input="handleCurrentLocationSearch" :placeholder="t('facebook.filter.searchLocation')" size="small" clearable prefix-icon="el-icon-search"></el-input>
                    <div class="filter-search-loading" v-if="esSearchLoading.currentLocation">
                      <i class="el-icon-loading"></i>
                      <span>{{ t('facebook.filter.loading', {}, '搜索中...') }}</span>
                    </div>
                  </div>
                  <el-checkbox :model-value="state.checkAll.currentLocation" @change="handleCurrentLocationCheckAllChange">{{ t('facebook.filter.all') }}</el-checkbox>
                  <el-divider></el-divider>
                  <!-- 使用checkbox-group来处理数组绑定 -->
                  <el-checkbox-group v-model="state.filters.currentLocations" @change="handleCurrentLocationItemChange">
                    <!-- 显示已选择的自定义项（来自ES搜索结果） -->
                    <template v-if="selectedCustomCurrentLocations.length > 0">
                      <div class="es-selected-items">
<!--                        <div class="es-result-divider">{{ t('facebook.filter.selected.custom', {}, '已选择的自定义项') }}</div>-->
                        <div v-for="item in selectedCustomCurrentLocations" :key="`selected-${item}`">
                          <el-checkbox :label="item">{{ item }}</el-checkbox>
                        </div>
                        <el-divider></el-divider>
                      </div>
                    </template>
                    
                    <!-- 显示预定义列表过滤后的项 -->
                    <div v-for="item in filteredCurrentLocations" :key="item.original">
                      <el-checkbox :label="item.original">
                        {{ getDisplayText(item) }}
                      </el-checkbox>
                    </div>
                    
                    <!-- 添加后端返回的位置数据 -->
                    <template v-if="esCurrentLocations.length > 0">
<!--                      <div class="es-result-divider">{{ t('facebook.filter.es.results', {}, '搜索结果') }}</div>-->
                      <div v-for="item in esCurrentLocations" :key="item">
                        <el-checkbox :label="item">{{ item }}</el-checkbox>
                      </div>
                    </template>
                  </el-checkbox-group>
                </div>
              </div>

              <!-- 家乡筛选 -->
              <div class="filter-group" :class="{ expanded: state.expanded.hometown }">
                <div class="filter-header" @click="toggleFilter('hometown')">
                  <span>{{ t('facebook.hometown') }}</span>
                  <i :class="['el-icon', state.expanded.hometown ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="state.expanded.hometown" class="filter-content">
                  <div class="filter-search" :class="{ 'is-loading': esSearchLoading.hometown }">
                    <el-input v-model="hometownSearch" @input="handleHometownSearch" :placeholder="t('facebook.filter.searchLocation')" size="small" clearable prefix-icon="el-icon-search"></el-input>
                    <div class="filter-search-loading" v-if="esSearchLoading.hometown">
                      <i class="el-icon-loading"></i>
                      <span>{{ t('facebook.filter.loading', {}, '搜索中...') }}</span>
                    </div>
                  </div>
                  <el-checkbox :model-value="state.checkAll.hometown" @change="handleHometownCheckAllChange">{{ t('facebook.filter.all') }}</el-checkbox>
                  <el-divider></el-divider>
                  <!-- 使用checkbox-group来处理数组绑定 -->
                  <el-checkbox-group v-model="state.filters.hometowns" @change="handleHometownItemChange">
                    <!-- 显示已选择的自定义项（来自ES搜索结果） -->
                    <template v-if="selectedCustomHometowns.length > 0">
                      <div class="es-selected-items">
<!--                        <div class="es-result-divider">{{ t('facebook.filter.selected.custom', {}, '已选择的自定义项') }}</div>-->
                        <div v-for="item in selectedCustomHometowns" :key="`selected-${item}`">
                          <el-checkbox :label="item">{{ item }}</el-checkbox>
                        </div>
                        <el-divider></el-divider>
                      </div>
                    </template>
                    
                    <!-- 显示预定义列表过滤后的项 -->
                    <div v-for="item in filteredHometowns" :key="item.original">
                      <el-checkbox :label="item.original">
                        {{ getDisplayText(item) }}
                      </el-checkbox>
                    </div>
                    
                    <!-- 添加后端返回的家乡数据 -->
                    <template v-if="esHometowns.length > 0">
<!--                      <div class="es-result-divider">{{ t('facebook.filter.es.results', {}, '搜索结果') }}</div>-->
                      <div v-for="item in esHometowns" :key="item">
                        <el-checkbox :label="item">{{ item }}</el-checkbox>
                      </div>
                    </template>
                  </el-checkbox-group>
                </div>
              </div>
              
              <!-- 关系状态筛选 -->
              <div class="filter-group" :class="{ expanded: state.expanded.relationshipStatus }">
                <div class="filter-header" @click="toggleFilter('relationshipStatus')">
                  <span>{{ t('facebook.relationship.status') }}</span>
                  <i :class="['el-icon', state.expanded.relationshipStatus ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="state.expanded.relationshipStatus" class="filter-content">
                  <div class="filter-search">
                    <el-input v-model="relationshipStatusSearch" :placeholder="t('facebook.filter.searchRelationship')" size="small" clearable prefix-icon="el-icon-search"></el-input>
                  </div>
                    <el-checkbox :model-value="state.checkAll.relationshipStatus" @change="handleRelationshipStatusCheckAllChange">{{ t('facebook.filter.all') }}</el-checkbox>
                  <el-divider></el-divider>
                  <!-- 使用checkbox-group来处理数组绑定 -->
                    <el-checkbox-group v-model="state.filters.relationshipStatuses" @change="handleRelationshipStatusItemChange">
                    <div v-for="item in filteredRelationshipStatuses" :key="item.zh">
                        <el-checkbox :label="item.zh">
                          {{ getDisplayText(item) }}
                        </el-checkbox>
                      </div>
                    </el-checkbox-group>
                </div>
              </div>

              <!-- 工作地点筛选 -->
              <div class="filter-group" :class="{ expanded: state.expanded.workplace }">
                <div class="filter-header" @click="toggleFilter('workplace')">
                  <span>{{ t('facebook.workplace') }}</span>
                  <i :class="['el-icon', state.expanded.workplace ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                </div>
                <div v-show="state.expanded.workplace" class="filter-content">
                  <div class="filter-search" :class="{ 'is-loading': esSearchLoading.workplace }">
                    <el-input v-model="workplaceSearch" @input="handleWorkplaceSearch" :placeholder="t('facebook.filter.searchWorkplace')" size="small" clearable prefix-icon="el-icon-search"></el-input>
                    <div class="filter-search-loading" v-if="esSearchLoading.workplace">
                      <i class="el-icon-loading"></i>
                      <span>{{ t('facebook.filter.loading', {}, '搜索中...') }}</span>
                    </div>
                  </div>
                  <el-checkbox :model-value="state.checkAll.workplace" @change="handleWorkplaceCheckAllChange">{{ t('facebook.filter.all') }}</el-checkbox>
                  <el-divider></el-divider>
                  <!-- 使用checkbox-group来处理数组绑定 -->
                  <el-checkbox-group v-model="state.filters.workplaces" @change="handleWorkplaceItemChange">
                    <!-- 显示已选择的自定义项（来自ES搜索结果） -->
                    <template v-if="selectedCustomWorkplaces.length > 0">
                      <div class="es-selected-items">
<!--                        <div class="es-result-divider">{{ t('facebook.filter.selected.custom', {}, '已选择的自定义项') }}</div>-->
                        <div v-for="item in selectedCustomWorkplaces" :key="`selected-${item}`">
                          <el-checkbox :label="item">{{ item }}</el-checkbox>
                        </div>
                        <el-divider></el-divider>
                      </div>
                    </template>
                    
                    <!-- 显示预定义列表过滤后的项 -->
                    <div v-for="item in filteredWorkplaces" :key="item.original">
                      <el-checkbox :label="item.original">
                        {{ getDisplayText(item) }}
                      </el-checkbox>
                    </div>
                    
                    <!-- 添加后端返回的工作地点数据 -->
                    <template v-if="esWorkplaces.length > 0">
<!--                      <div class="es-result-divider">{{ t('facebook.filter.es.results', {}, '搜索结果') }}</div>-->
                      <div v-for="item in esWorkplaces" :key="item">
                        <el-checkbox :label="item">{{ item }}</el-checkbox>
                      </div>
                    </template>
                  </el-checkbox-group>
                </div>
              </div>
              
              <!-- 联系方式筛选 -->
              <div class="filter-group" :class="{ expanded: state.expanded.contactMethod }">
                <div class="filter-header" @click="toggleFilter('contactMethod')">
                  <span>{{ t('facebook.filter.contactMethod') }}</span>
                  <i :class="['el-icon', state.expanded.contactMethod ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
                  </div>
                <div v-show="state.expanded.contactMethod" class="filter-content">
                  <el-checkbox :model-value="state.checkAll.contactMethod" @change="handleContactMethodCheckAllChange">{{ t('facebook.filter.all') }}</el-checkbox>
                  <el-divider></el-divider>
                    <el-checkbox-group v-model="state.filters.contactMethods" @change="handleContactMethodChange">
                    <div v-for="method in ['email', 'phone']" :key="method">
                        <el-checkbox :label="method">
                          {{ method === 'email' ? t('facebook.contact.email') : t('facebook.contact.phone') }}
                        </el-checkbox>
                      </div>
                    </el-checkbox-group>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 右侧数据内容 -->
          <div class="data-content">
            <!-- 操作按钮 -->
            <div class="action-bar">
              <!-- 符合条件的数量显示 -->
              <div class="matched-count">
                <span>{{ t('facebook.matched.count') }}</span>
                <span class="matched-count-number" v-loading="countLoading">{{ formatNumber(displayedCount) }}</span>
                <span>{{ t('facebook.matched.count.unit') }}</span>
              </div>
              <div class="export-container">
                <el-button @click="handleMatch" class="match-btn" style="margin-right: 10px;">
                  <el-icon><Upload /></el-icon>
                  {{ t('facebook.match') }}
                </el-button>
                <el-button @click="handleExport" class="export-btn" :loading="exportLoading">
                  <el-icon><Download /></el-icon>
                  {{ t('facebook.export') }}
                </el-button>
              </div>
            </div>
            
            <!-- 卡片式联系人列表 -->
            <div v-loading="state.loading" class="contact-card-list">
              <!-- 隐藏和移除"没有找到符合条件的联系人"的提示 -->
              <!-- 只在明确完成加载且没有数据时才显示 -->
              <div v-if="!state.loading && filteredContacts.length === 0" class="no-data">
                <i class="el-icon-warning-outline"></i>
                <p>{{ t('facebook.no.data') }}</p>
              </div>
              <!-- 添加一个占位骨架屏，在加载中且无数据时显示 -->
              <div v-if="state.loading && filteredContacts.length === 0" class="skeleton-loading">
                <div v-for="i in 5" :key="i" class="skeleton-card">
                  <div class="skeleton-header">
                    <div class="skeleton-avatar"></div>
                    <div class="skeleton-title"></div>
                  </div>
                  <div class="skeleton-content">
                    <div class="skeleton-line"></div>
                    <div class="skeleton-line"></div>
                    <div class="skeleton-line"></div>
                  </div>
                </div>
              </div>
              <div 
                v-for="contact in paginatedContacts" 
                :key="contact.phoneNumber || contact.id" 
                class="contact-card"
              >
                <!-- 卡片头部 -->
                <div class="card-header">
                  <div class="avatar-name-container">
                    <div class="avatar-container">
                      <el-avatar 
                        :size="40" 
                        :src="contact.avatar || getRandomAvatar(contact.phoneNumber, contact.fullName)" 
                        class="contact-avatar"
                        @error="handleAvatarError"
                      >
                        {{ getNameInitial(contact) }}
                      </el-avatar>
                    </div>
                    <div class="header-info">
                      <div class="contact-name">{{ getFullName(contact) }}</div>
                    </div>
                  </div>
                  <div class="detail-button-container">
                    <el-button
                      class="detail-btn"
                      @click="toggleContactDetails(contact)"
                      :loading="contact.loading"
                      :disabled="contact.loading"
                    >
                      {{ contact.loading ? '加载中...' : (contact.expanded ? t('facebook.collapse') : t('facebook.details')) }}
                    </el-button>
                  </div>
                </div>
                
                <!-- 卡片内容 -->
                <div class="card-content" v-if="!contact.expanded">
                  <!-- 基础信息（简要显示） -->
                  <div class="basic-info">
                    <!-- 性别信息 -->
                    <div class="info-row" v-if="contact.gender">
                      <div class="info-label">{{ t('facebook.gender') }}:</div>
                      <div class="info-value">{{ formatGender(contact.gender) }}</div>
                    </div>
                    
                    <div class="info-row" v-if="contact.currentLocation">
                      <div class="info-label">{{ t('facebook.current.location') }}:</div>
                      <div class="info-value">
                        <img v-if="contact.currentLocation && contact.currentLocation.includes('USA')" src="https://flagcdn.com/w20/us.png" class="country-flag" />
                        {{ formatLocation(contact.currentLocation) }}
                      </div>
                    </div>
                    
                    <div class="info-row" v-if="contact.hometown">
                      <div class="info-label">{{ t('facebook.hometown') }}:</div>
                      <div class="info-value">
                        {{ formatLocation(contact.hometown) }}
                      </div>
                    </div>
                    
                    <div class="info-row" v-if="contact.relationshipStatus">
                      <div class="info-label">{{ t('facebook.relationship.status') }}:</div>
                      <div class="info-value">
                        {{ contact.relationshipStatus }}
                      </div>
                    </div>
                    
                    <div class="info-row" v-if="contact.workplace">
                      <div class="info-label">{{ t('facebook.workplace') }}:</div>
                      <div class="info-value">
                        {{ contact.workplace }}
                      </div>
                    </div>
                    
                    <!-- 添加Facebook ID链接在简洁视图中 -->
                    <div class="info-row" v-if="contact.facebookId">
                      <div class="info-label">Facebook:</div>
                      <div class="info-value">
                        <a :href="getFacebookProfileUrl(contact.facebookId)" target="_blank" class="facebook-link">
                          {{ t('facebook.look.file') }}
                          <span class="external-link-icon">
                            <i class="el-icon-link"></i>
                          </span>
                        </a>
                      </div>
                    </div>
                    
                    <!-- 联系方式（完整显示）- 合并邮箱和电话 -->
                    <div class="info-row" v-if="contact.email || contact.phoneNumber">
                      <div class="info-label">{{ t('facebook.contact.info') }}:</div>
                      <div class="info-value contact-method">
                        <span v-if="contact.email">{{ contact.email }}</span>
                        <span v-if="contact.email && contact.phoneNumber"> / </span>
                        <span v-if="contact.phoneNumber">{{ formatPhoneNumber(contact.phoneNumber) }}</span>
                      </div>
                    </div>
                  </div>
                </div>
                
                <!-- 展开后显示完整信息 -->
                <div class="card-content" v-if="contact.expanded">
                  <!-- 加载状态显示 -->
                  <div v-if="contact.loading" class="loading-container">
                    <el-icon class="is-loading">
                      <Loading />
                    </el-icon>
                    <span class="loading-text">{{ t('facebook.loading') }}</span>
                  </div>

                  <!-- 详细信息（完整显示） -->
                  <div class="detailed-info" v-else>
                    <!-- 基本信息部分 -->
                    <div class="info-row" v-if="hasValidValue(contact.gender)">
                      <div class="info-label">{{ t('facebook.gender') }}:</div>
                      <div class="info-value">{{ formatGender(contact.gender) }}</div>
                    </div>

                    <div class="info-row" v-if="hasValidValue(contact.currentLocation)">
                      <div class="info-label">{{ t('facebook.current.location') }}:</div>
                      <div class="info-value">
                        <img v-if="contact.currentLocation && contact.currentLocation.includes('USA')" src="https://flagcdn.com/w20/us.png" class="country-flag" />
                        {{ formatLocation(contact.currentLocation) }}
                      </div>
                    </div>

                    <div class="info-row" v-if="hasValidValue(contact.hometown)">
                      <div class="info-label">{{ t('facebook.hometown') }}:</div>
                      <div class="info-value">
                        {{ formatLocation(contact.hometown) }}
                      </div>
                    </div>

                    <div class="info-row" v-if="hasValidValue(contact.relationshipStatus)">
                      <div class="info-label">{{ t('facebook.relationship.status') }}:</div>
                      <div class="info-value">
                        {{ contact.relationshipStatus }}
                      </div>
                    </div>

                    <div class="info-row" v-if="hasValidValue(contact.workplace)">
                      <div class="info-label">{{ t('facebook.workplace') }}:</div>
                      <div class="info-value">
                        {{ contact.workplace }}
                      </div>
                    </div>
                    
                    <!-- 联系方式部分（完整显示）- 合并邮箱和电话 -->
                    <div class="info-row" v-if="hasValidValue(contact.email) || hasValidValue(contact.phoneNumber)">
                      <div class="info-label">{{ t('facebook.contact.info') }}:</div>
                      <div class="info-value contact-method">
                        <span v-if="hasValidValue(contact.email)">{{ contact.email }}</span>
                        <span v-if="hasValidValue(contact.email) && hasValidValue(contact.phoneNumber)"> / </span>
                        <span v-if="hasValidValue(contact.phoneNumber)">{{ formatPhoneNumber(contact.phoneNumber) }}</span>
                      </div>
                    </div>

                    <!-- 添加详细信息标题 -->
                    <div class="section-divider">
                      <div class="section-title">{{ t('facebook.details.info') }}</div>
                    </div>

                    <!-- 添加Facebook ID -->
                    <div class="info-row" v-if="hasValidValue(contact.facebookId)">
                      <div class="info-label">{{ t('facebook.id') }}:</div>
                      <div class="info-value">
                        <a :href="getFacebookProfileUrl(contact.facebookId)" target="_blank" class="facebook-link">
                          {{ contact.facebookId }}
                          <span class="external-link-icon">
                            <i class="el-icon-link"></i>
                          </span>
                        </a>
                        <el-button
                          size="mini"
                          type="text"
                          class="copy-link-btn"
                          @click="copyToClipboard(getFacebookProfileUrl(contact.facebookId))"
                        >
                          {{ t('facebook.copy.link') }}
                        </el-button>
                      </div>
                    </div>

                    <!-- 添加日期信息 -->
                    <div class="info-row" v-if="hasValidValue(contact.date)">
                      <div class="info-label">{{ t('facebook.update.date') }}:</div>
                      <div class="info-value">{{ formatDatetime(contact.date) }}</div>
                    </div>

                    <!-- 添加加入日期信息 -->
                    <div class="info-row" v-if="hasValidValue(contact.joinDate)">
                      <div class="info-label">{{ t('facebook.join.date') }}:</div>
                      <div class="info-value">{{ formatDatetime(contact.joinDate) }}</div>
                    </div>

                    <!-- 动态显示其他字段（排除已显示的字段） -->
                    <div v-for="(value, key) in getAdditionalFields(contact)" :key="key" class="info-row">
                      <div class="info-label">{{ getFieldLabel(key) }}:</div>
                      <div class="info-value">{{ formatFieldValue(key, value) }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="state.queryParams.pageNum"
                :page-sizes="[10, 20, 50]"
                :page-size="state.queryParams.pageSize"
                layout="sizes, prev, pager, next, jumper"
                :total="Math.max(total, 1)"
                background
                :pager-count="7"
                :disabled="state.loading"
              >
              </el-pagination>
            </div>
          </div>
        </div>
      
        <!-- 添加到线索弹窗 -->
        <el-dialog
          v-model="addLeadDialog"
          :title="t('facebook.addToLeads')"
          width="30%"
          @close="addLeadDialog = false"
        >
          <el-form :model="leadForm">
            <el-form-item :label="t('facebook.remarks')">
              <el-input
                v-model="leadForm.remarks"
                type="textarea"
                :placeholder="t('enterRemarks')"
              ></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="addLeadDialog = false">{{ t('cancel') }}</el-button>
              <el-button type="primary" @click="submitAddToLeads">{{ t('confirm') }}</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
  
  <!-- 导出对话框 -->
  <el-dialog
    v-model="exportDialogVisible"
    :title="t('export.dialog.title')"
    width="400px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="export-dialog-content">
      <div class="export-info">
        <p>{{ t('export.matched.records') }}: <span class="export-highlight">{{ totalMatchCount }}</span></p>
        <p>{{ t('export.current.balance') }}: <span class="export-highlight">{{ userBalance.exportQuotaRemaining }}</span></p>
        <p class="export-note">{{ t('export.consumption.notice') }}</p>
        <p class="export-limit-notice">{{ t('export.max.limit.notice') }}</p>
      </div>
      
      <div class="export-input">
        <p>{{ t('export.enter.count') }}:</p>
        <el-input-number
          v-model="exportCount"
          :min="1"
          :max="Math.max(1, Math.min(totalMatchCount.value, 50000, userBalance.exportQuotaRemaining || 1))"
          :step="100"
          size="large"
          controls-position="right"
        />
        
        <div class="export-warnings">
          <p v-if="isExportCountExceeded" class="export-warning">
            <i class="el-icon-warning-outline"></i>
            {{ t('export.warning.count.exceeded') }}
          </p>
          <p v-if="isBalanceInsufficient" class="export-warning">
            <i class="el-icon-warning-outline"></i>
            {{ t('export.warning.insufficient.balance') }}
          </p>
        </div>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="exportDialogVisible = false">{{ t('cancel') }}</el-button>
        <el-button 
          type="primary" 
          @click="doExport" 
          :loading="exportLoading"
          :disabled="isExportCountExceeded || isBalanceInsufficient || isExportLimitExceeded || !exportCount"
        >
          {{ t('export.confirm') }}
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 添加匹配对话框 -->
  <el-dialog
    v-model="matchDialogVisible"
    :title="t('facebook.match.data')"
    width="700px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="match-dialog-content">
      <el-tabs v-model="activeMatchTab">
        <el-tab-pane :label="t('facebook.match.upload')" name="upload">
          <div class="match-info">
            <p>{{ t('facebook.match.select.file') }}：</p>
            
            <!-- 匹配方式选择 -->
            <div class="match-type-select">
              <p>{{ t('facebook.match.type') }}：</p>
              <el-radio-group v-model="matchType" @change="handleMatchTypeChange">
                <el-radio :label="1">{{ t('facebook.match.type.1') }}</el-radio>
                <el-radio :label="2">{{ t('facebook.match.type.2') }}</el-radio>
                <el-radio :label="3">{{ t('facebook.match.type.3') }}</el-radio>
                <el-radio :label="4">{{ t('facebook.match.type.4') }}</el-radio>
              </el-radio-group>
            </div>
            
            <!-- 文件上传 -->
            <div class="file-upload-container">
              <p>{{ t('facebook.match.upload.file') }}：</p>
              <el-upload
                class="upload-demo"
                drag
                action="#"
                :http-request="uploadFile"
                :before-upload="beforeUpload"
                :on-change="handleFileChange"
                :auto-upload="false"
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="fileList"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  {{ t('facebook.match.drag.file') }} <em>{{ t('facebook.match.click.upload') }}</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    {{ t('facebook.match.file.tip') }}
                  </div>
                </template>
              </el-upload>
            </div>
            
            <!-- 模板下载 -->
            <div class="template-download">
              <el-button type="text" @click="downloadTemplate">{{ t('facebook.match.download.template') }}</el-button>
            </div>
            
            <!-- 匹配进度 -->
            <div v-if="matchProgress > 0" class="match-progress">
              <p>{{ t('facebook.match.progress') }}：</p>
              <el-progress :percentage="matchProgress" :stroke-width="15"></el-progress>
            </div>
            
            <!-- 匹配结果 -->
            <div v-if="matchResult.total > 0" class="match-result">
              <p>{{ t('facebook.match.result') }}：</p>
              <div class="result-stats">
                <p>{{ t('facebook.match.total') }}：<span>{{ matchResult.total }}</span></p>
                <p>{{ t('facebook.match.success') }}：<span class="match-success">{{ matchResult.matched }}</span></p>
                <p>{{ t('facebook.match.fail') }}：<span class="match-fail">{{ matchResult.unmatched }}</span></p>
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane :label="t('facebook.match.history')" name="history">
          <div class="match-history">
            <el-table :data="matchRecords" style="width: 100%" v-loading="historyLoading">
              <el-table-column :prop="'createTime'" :label="t('facebook.match.time')" width="180">
                <template #default="scope">
                  {{ formatDateTime(scope.row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column :prop="'matchType'" :label="t('facebook.match.type.label')" width="180">
                <template #default="scope">
                  {{ getMatchTypeText(scope.row.matchType) }}
                </template>
              </el-table-column>
              <el-table-column :prop="'totalRecords'" :label="t('facebook.match.total.records')" width="100"></el-table-column>
              <el-table-column :prop="'matchedRecords'" :label="t('facebook.match.matched.records')" width="120"></el-table-column>
              <el-table-column :label="t('facebook.match.operation')">
                <template #default="scope">
                  <el-button @click="downloadHistoryResult(scope.row.id)" type="primary" size="small">
                    {{ t('facebook.match.download.result') }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              @size-change="handleHistorySizeChange"
              @current-change="handleHistoryCurrentChange"
              :current-page="historyPage.current"
              :page-sizes="[5, 10, 20, 50]"
              :page-size="historyPage.size"
              layout="sizes, prev, pager, next, jumper"
              :total="historyPage.total"
              class="pagination-container"
            >
            </el-pagination>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <!-- 将匹配对话框底部按钮移到这里，作为对话框的footer -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="matchDialogVisible = false">{{ t('cancel') }}</el-button>
        <el-button 
          type="primary" 
          @click="startMatch" 
          :loading="matchLoading"
          :disabled="!fileSelected || matchLoading"
          v-if="activeMatchTab === 'upload'"
          style="background-color: #1877f2; font-weight: bold;"
        >
          {{ t('facebook.start.match') }}
        </el-button>
        <el-button 
          type="success" 
          @click="downloadMatchResult" 
          :disabled="!matchResultFile"
          v-if="matchResultFile && activeMatchTab === 'upload'"
        >
          {{ t('facebook.match.download') }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Download, Upload, Loading } from '@element-plus/icons-vue'
import { t, addTranslation, currentLanguage } from '@/utils/i18n'
import { ElDialog } from 'element-plus'
import { ElDivider } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'

import MainHeader from '@/components/MainHeader.vue'
import SideMenu from '@/components/SideMenu.vue'

import {
  getFacebookList,
  getFacebookDetailByTableAndId,
  exportFacebookData,
  addToLeads,
  searchFacebook,
  getFacebookCount,
  getUserBalanceInfo,
  matchFacebookData, // 匹配API
  getMatchRecords, // 获取匹配历史记录
  searchCurrentLocationsFromES,  // 新增：从ES查询当前所在地
  searchHometownsFromES,         // 新增：从ES查询家乡
  searchWorkplacesFromES         // 新增：从ES查询工作地点
} from '@/api/facebook'
import {getCurrentLanguage} from "../utils/i18n";

const router = useRouter()

// 页面状态
const state = reactive({
  // 查询参数
  queryParams: {
    name: '',
    gender: '',
    currentLocation: '',
    hometown: '',
    relationshipStatus: '',
    workplace: '',
    email: '',
    phone: '',
    pageNum: 1,
    pageSize: 10,
    contactMethod: ''
  },
  
  // 加载状态
  loading: false,
  initialized: false, // 添加初始化标志
  
  // 数据列表
  contactsList: [],
  
  // 数据总数
  total: 0,
  
  // 展开的筛选条件
  expanded: {
    gender: false,
    currentLocation: false,
    hometown: false,
    relationshipStatus: false,
    workplace: false,
    contactMethod: false
  },
  
  // 筛选状态 - 设置为空数组表示都不选中
  filters: {
    genders: [],
    currentLocations: [],
    hometowns: [],
    relationshipStatuses: [],
    workplaces: [],
    contactMethods: []
  },
  
  // 全选状态 - 设置为false表示不全选
  checkAll: {
    gender: false,
    currentLocation: false,
    hometown: false,
    relationshipStatus: false,
    workplace: false,
    contactMethod: false
  },
  
  expandedCards: {},
  selectedIds: [],
  allCurrentLocations: [], // 所有当前位置
  allHometowns: [], // 所有家乡
  allRelationshipStatuses: [], // 所有关系状态
  allWorkplaces: [] // 所有工作地点
})

// 筛选词
const currentLocationSearch = ref('')
const hometownSearch = ref('')
const relationshipStatusSearch = ref('')
const workplaceSearch = ref('')

// 预定义的家乡城市列表
const predefinedHometowns = [
  { zh: '地拉那', en: 'Tirana', original: 'Tirana, Albania' },
  { zh: '都拉斯', en: 'Durrës', original: 'Durrës' },
  { zh: '斯库台', en: 'Shkodër', original: 'Shkodër, Albania' },
  { zh: '克鲁亚', en: 'Krujë', original: 'Krujë' },
  { zh: '费里', en: 'Fier', original: 'Fier' },
  { zh: '萨兰达', en: 'Sarandë', original: 'Sarandë' },
  { zh: '埃尔巴桑', en: 'Elbasan', original: 'Elbasan, Albania' },
  { zh: '吉罗卡斯特', en: 'Gjirokastër', original: 'Gjirokastër' },
  { zh: '达卡', en: 'Dhaka', original: 'Dhaka, Bangladesh' },
  { zh: '吉大港', en: 'Chittagong', original: 'Chittagong' },
  { zh: '库尔纳', en: 'Khulna', original: 'Khulna' },
  { zh: '库米拉', en: 'Comilla', original: 'Comilla' },
  { zh: '锡尔赫特', en: 'Sylhet', original: 'Sylhet' },
  { zh: '科克斯巴扎尔', en: "Cox's Bazar", original: "Cox's Bazar, Bangladesh" },
  { zh: '圣地亚哥', en: 'Santiago', original: 'Santiago, Chile' },
  { zh: '瓦尔帕莱索', en: 'Valparaíso', original: 'Valparaíso, Chile' },
  { zh: '比尼亚德尔马', en: 'Viña del Mar', original: 'Viña del mar, Chile' },
  { zh: '康塞普西翁', en: 'Concepción', original: 'Concepción, Chile' },
  { zh: '伊基克', en: 'Iquique', original: 'Iquique, Chile' },
  { zh: '普恩特阿尔托', en: 'Puente Alto', original: 'Puente Alto, Chile' },
  { zh: '利马', en: 'Lima', original: 'Lima, Peru' },
  { zh: '纽约', en: 'New York', original: 'New York, New York' },
  { zh: '迪拜', en: 'Dubai', original: 'Dubai, United Arab Emirates' },
  { zh: '伦敦', en: 'London', original: 'London, United Kingdom' },
  { zh: '阿姆斯特丹', en: 'Amsterdam', original: 'Amsterdam, Netherlands' },
  { zh: '柏林', en: 'Berlin', original: 'Berlin, Germany' },
  { zh: '法兰克福', en: 'Frankfurt', original: 'Frankfurt, Germany' },
  { zh: '米兰', en: 'Milan', original: 'Milan, Italy' },
  { zh: '耶路撒冷', en: 'Jerusalem', original: 'Jerusalem, Israel' },
  { zh: '上海', en: 'Shanghai', original: 'Shanghai, China' },
  { zh: '深圳', en: 'Shenzhen', original: 'Shenzhen, China' },
  { zh: '广州', en: 'Guangzhou', original: 'Guangzhou, China' },
  { zh: '香港', en: 'Hong Kong', original: 'Hong Kong' },
  { zh: '澳门', en: 'Macao', original: 'Macao, China' },
  { zh: '台湾', en: 'Taiwan', original: 'Taiwan' },
  { zh: '北京', en: 'Beijing', original: 'Beijing, China' }
]

// 预定义的当前所在地城市列表
const predefinedCurrentLocations = [
  { zh: '地拉那', en: 'Tirana', original: 'Tirana, Albania' },
  { zh: '都拉斯', en: 'Durrës', original: 'Durrës' },
  { zh: '斯库台', en: 'Shkodër', original: 'Shkodër, Albania' },
  { zh: '吉大港', en: 'Chittagong', original: 'Chittagong' },
  { zh: '达卡', en: 'Dhaka', original: 'Dhaka, Bangladesh' },
  { zh: '库尔纳', en: 'Khulna', original: 'Khulna' },
  { zh: '库米拉', en: 'Comilla', original: 'Comilla' },
  { zh: '锡尔赫特', en: 'Sylhet', original: 'Sylhet' },
  { zh: '科克斯巴扎尔', en: "Cox's Bazar", original: "Cox's Bazar, Bangladesh" },
  { zh: '圣地亚哥', en: 'Santiago', original: 'Santiago, Chile' },
  { zh: '伊基克', en: 'Iquique', original: 'Iquique, Chile' },
  { zh: '瓦尔帕莱索', en: 'Valparaíso', original: 'Valparaíso, Chile' },
  { zh: '比尼亚德尔马', en: 'Viña del Mar', original: 'Viña del mar, Chile' },
  { zh: '塔尔卡', en: 'Talca', original: 'Talca, Chile' },
  { zh: '科金博', en: 'Coquimbo', original: 'Coquimbo, Chile' },
  { zh: '利马', en: 'Lima', original: 'Lima, Peru' },
  { zh: '纽约', en: 'New York', original: 'New York, New York' },
  { zh: '拉斯维加斯', en: 'Las Vegas', original: 'Las Vegas, Nevada' },
  { zh: '圣保罗', en: 'São Paulo', original: 'São Paulo, Brazil' },
  { zh: '耶路撒冷', en: 'Jerusalem', original: 'Jerusalem, Israel' },
  { zh: '海法', en: 'Haifa', original: 'Haifa, Israel' },
  { zh: '贝尔谢巴', en: 'Beersheba', original: 'Beersheba, Israel' },
  { zh: '米兰', en: 'Milan', original: 'Milan, Italy' },
  { zh: '德里', en: 'Delhi', original: 'Delhi, India' },
  { zh: '海得拉巴', en: 'Hyderabad', original: 'Hyderabad' },
  { zh: '艾哈迈达巴德', en: 'Ahmedabad', original: 'Ahmedabad, India' },
  { zh: '迈索尔', en: 'Mysore', original: 'Mysore, Karnataka' },
  { zh: '瓦尔纳西', en: 'Varanasi', original: 'Varanasi, India' },
  { zh: '里加', en: 'Riga', original: 'Riga, Latvia' },
  { zh: '太子港', en: 'Port-au-Prince', original: 'Port-au-Prince, Haiti' },
  { zh: '深圳', en: 'Shenzhen', original: 'Shenzhen, China' },
  { zh: '广州', en: 'Guangzhou', original: 'Guangzhou, China' },
  { zh: '香港', en: 'Hong Kong', original: 'Hong Kong' },
  { zh: '澳门', en: 'Macao', original: 'Macao, China' },
  { zh: '台湾', en: 'Taiwan', original: 'Taiwan' },
  { zh: '北京', en: 'Beijing', original: 'Beijing, China' }
]

// 预定义的工作地点列表
const predefinedWorkplaces = [
  { zh: '自雇', en: 'Self-Employed', original: 'Self-Employed' },
  { zh: '联邦调查局', en: 'FBI', original: 'F.B.I.' },
  { zh: '脸书', en: 'Facebook', original: 'Facebook' },
  { zh: '诺斯罗普·格鲁曼公司', en: 'Northrop Grumman', original: 'Northrop Grumman' },
  { zh: 'AC米兰', en: 'AC Milan', original: 'AC Milan' },
  { zh: '学生', en: 'Student', original: 'Student' },
  { zh: '家庭主妇', en: 'Housewife', original: 'Housewife' },
  { zh: '阿尔巴尼亚电信', en: 'Albtelecom', original: 'albtelecom' },
  { zh: '孟加拉国空军学院', en: 'Bangladesh Air Force Academy', original: 'Bangladesh Air Force Academy' },
  { zh: 'IDP 雅思精华', en: 'IELTS Essentials from IDP', original: 'IELTS Essentials from IDP' },
  { zh: '同步金融', en: 'Synchrony Financial', original: 'Synchrony Financial - Formerly GE Capital Bank' },
  { zh: 'Pathao', en: 'Pathao', original: 'Pathao' },
  { zh: 'NBA', en: 'NBA', original: 'NBA' },
  { zh: '宝莱纳', en: 'Paulaner', original: 'Paulaner' },
  { zh: '梅赛德斯·奔驰', en: 'Mercedes Benz', original: 'Mercedes-Benz' },
  { zh: '达卡大学', en: 'University of Dhaka', original: 'University of Dhaka' },
  { zh: 'ISKCON 国际克里希纳意识协会', en: 'ISKCON International Society for Krishna Consciousness', original: 'ISKCON International Society for Krishna Consciousness' },
  { zh: 'Daraz 在线购物', en: 'Daraz Online Shopping', original: 'Daraz Online Shopping' },
  { zh: '喜来登四点酒店', en: 'Four Points by Sheraton', original: 'Four Points by Sheraton Dhaka Gulshan' },
  { zh: '油管', en: 'YouTube', original: 'YouTube' },
  { zh: '吉大港医学院', en: 'Chittagong Medical College', original: 'Chittagong Medical College' },
  { zh: '地拉那国际酒店与会议中心', en: 'Tirana International Hotel & Conference Centre', original: 'Tirana International Hotel & Conference Centre' },
  { zh: 'RTSH (阿尔巴尼亚广播电视台)', en: 'RTSH', original: 'RTSH' },
  { zh: '阿尔巴尼亚邮政', en: 'Albanian Post', original: 'Posta Shqiptare' },
  { zh: '城市银行有限公司', en: 'The City Bank Limited', original: 'The City Bank Limited' },
  { zh: '乌塔拉银行有限公司', en: 'Uttara Bank Limited', original: 'Uttara Bank Limited' }
]

// 预定义的关系状态列表
const predefinedRelationshipStatuses = [
  { zh: '已婚', en: 'Married', original: ['已婚', 'Married', 'Menikah', 'แต่งงานแล้ว'] },
  { zh: '单身', en: 'Single', original: ['单身', 'Single', 'Lajang', 'โสด', 'عزباء'] },
  { zh: '恋爱中', en: 'In a relationship', original: ['恋爱中', 'In a relationship', 'Berpacaran'] },
  { zh: '已订婚', en: 'Engaged', original: ['已订婚', 'Engaged'] },
  { zh: '情况复杂', en: "It's complicated", original: ['情况复杂', "It's complicated", 'Rumit'] },
  { zh: '分居', en: 'Separated', original: ['分居', 'Separated'] },
  { zh: '寡居', en: 'Widowed', original: ['寡居', 'Widowed'] },
  { zh: '开放式关系', en: 'In an open relationship', original: ['开放式关系', 'In an open relationship'] }
]

// 国际化显示文本方法 - 根据当前语言返回对应的显示文本
const getDisplayText = (item) => {
  return currentLanguage.value === 'zh' ? item.zh : item.en
}

// 获取关系状态的所有语言版本 - 用于向后端传输
const getAllRelationshipStatusValues = (selectedStatuses) => {
  const allValues = []
  selectedStatuses.forEach(selectedZh => {
    const status = predefinedRelationshipStatuses.find(s => s.zh === selectedZh)
    if (status) {
      allValues.push(...status.original)
    }
  })
  return [...new Set(allValues)] // 去重
}

// 构建关系状态多选筛选参数 - 特殊处理多语言值
const buildRelationshipStatusParam = (selectedItems, allItems, fieldName) => {
  // 情况1：没有选择任何项
  if (!selectedItems || selectedItems.length === 0) {
    return '';
  }

  // 情况2：选择了所有项
  if (selectedItems.length === allItems.length) {
    return '';
  }

  // 情况3：选择了部分项 - 获取所有语言版本
  const allValues = getAllRelationshipStatusValues(selectedItems);
  const result = allValues.join('、');
  return result;
}

// 联系人弹窗状态
const addLeadDialog = ref(false)
const leadForm = reactive({
  contactId: '',
  remarks: ''
})

// 分页后的显示数据 - 确保每个联系人都有expanded属性
const paginatedContacts = computed(() => {
  // 每次重新计算时，确保使用最新数据
  return state.contactsList.map(contact => ({
    ...contact,
    expanded: contact.expanded || false
  }));
});

// 根据筛选条件过滤数据的计算属性
const filteredContacts = computed(() => {
  // 直接返回后端筛选后的结果，前端不再进行额外筛选
  return state.contactsList;
});

// 总页数
const total = computed(() => {
  return state.total
})



// 使用防抖函数
const debounce = (fn, delay) => {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 处理姓名输入变化，添加防抖功能
const handleNameInputChange = debounce(() => {
  state.queryParams.pageNum = 1;
  searchByKeyword();
}, 500);

// 构建多选筛选参数
const buildMultiSelectParam = (selectedItems, allItems, fieldName) => {
  // 情况1：没有选择任何项
  if (!selectedItems || selectedItems.length === 0) {
    return '';
  }

  // 情况2：全选（选中项数量等于所有可用项数量）
  if (allItems && selectedItems.length === allItems.length) {
    return '';
  }

  // 情况3：部分选择（包括单选和多选）- 使用中文顿号分隔
  const result = selectedItems.join('、');
  return result;
};

// 构建性别筛选参数（特殊处理）
const buildGenderParam = (selectedGenders) => {
  // 情况1：没有选择任何性别
  if (!selectedGenders || selectedGenders.length === 0) {
    return '';
  }

  // 情况2：选择了所有性别（M和F）
  if (selectedGenders.length === 2) {
    return '';
  }

  // 情况3：选择了单个性别
  const result = selectedGenders[0];
  return result;
};

// 判断是否有筛选条件
const hasFilterConditions = (params) => {
  // 检查4个主要筛选字段
  const filterFields = [
    'currentLocation',
    'hometown',
    'relationshipStatus',
    'workplace',
    'gender',
    'contactMethod'
  ];

  // 如果任何一个筛选字段有值，就认为有筛选条件
  const hasFilters = filterFields.some(field => {
    const value = params[field];
    return value && value.trim() !== '';
  });

  return hasFilters;
};

// 搜索Facebook联系人
const searchByKeyword = async (retry = false) => {
  // 仅当不是重试时，才阻止并发请求；重试调用允许穿透 loading 限制
  if ((state.loading && !retry) || !state.initialized) return; // 防止重复请求和未初始化时的请求
  
  try {
    state.loading = true;
    countLoading.value = true; // 添加数量加载状态
    
    // 清空当前列表，确保筛选时不会保留旧数据
    state.contactsList = [];
    
    // 重置所有展开状态
    state.expandedCards = {};
    
    // 验证分页参数
    if (state.queryParams.pageNum < 1) {
      state.queryParams.pageNum = 1;
    }
    if (state.queryParams.pageSize < 1) {
      state.queryParams.pageSize = 10;
    }

    // 构建查询参数，使用与导出一致的参数格式
    const searchParams = {
      // 基本搜索参数
      name: state.queryParams.name || '',
      pageNum: state.queryParams.pageNum,
      pageSize: state.queryParams.pageSize,

      // 筛选参数 - 使用后端期望的字段名
      gender: buildGenderParam(state.filters.genders),

      // 当前位置筛选参数 - 支持多选
      currentLocation: buildMultiSelectParam(
        state.filters.currentLocations,
        state.allCurrentLocations,
        '当前所在地'
      ),

      // 家乡筛选参数 - 支持多选
      hometown: buildMultiSelectParam(
        state.filters.hometowns,
        state.allHometowns,
        '家乡'
      ),

      // 关系状态筛选参数 - 支持多选多语言
      relationshipStatus: buildRelationshipStatusParam(
        state.filters.relationshipStatuses,
        state.allRelationshipStatuses,
        '关系状态'
      ),

      // 工作地点筛选参数 - 支持多选
      workplace: buildMultiSelectParam(
        state.filters.workplaces,
        state.allWorkplaces,
        '工作地点'
      ),

      // 联系方式筛选参数
      contactMethod: state.filters.contactMethods.length === 0 ? '' :
                     state.filters.contactMethods.length === 2 ? 'any' :
                     state.filters.contactMethods[0]
    };

    // 判断是否有筛选条件，决定使用哪个API接口
    const hasFilters = hasFilterConditions(searchParams);

    // 根据是否有筛选条件选择不同的API接口
    const response = hasFilters
      ? await searchFacebook(searchParams)  // 有筛选条件时使用search接口
      : await getFacebookList(searchParams); // 无筛选条件时使用list接口

    if (response && response.code === 200) {
      // 处理后端返回的数据格式
      const responseData = response.data && response.data.data ? response.data.data : response.data;
      // 获取原始列表数据
      const rawList = responseData.list || [];

      // 检查数据质量
      let validDataCount = 0;
      let invalidDataCount = 0;

      rawList.forEach((contact, index) => {
        const contactId = contact.id || contact.phoneNumber;
        if (contactId) {
          validDataCount++;
        } else {
          invalidDataCount++;
        }
      });

      // 直接使用后端返回的原始数据，不进行去重处理
      const finalList = rawList.map(contact => ({
        ...contact,
        expanded: state.expandedCards[contact.id || contact.phoneNumber] || false
      }));

      // 更新列表数据
      state.contactsList = finalList;


      // 修复分页数据：优先使用后端返回的total，确保分页计算正确
      if (responseData.total !== undefined && responseData.total !== null) {
        state.total = Math.max(responseData.total, 1);
      } else {
        // 如果后端没有返回total，保持原有total值，避免错误计算
        // 如果是第一次加载且没有total，设置为1
        if (state.total === 0 && state.queryParams.pageNum === 1) {
          state.total = 1; // 设置为1而不是0，确保分页控件显示
        }
      }
      
      // 确保total至少为0，即使没有数据也显示分页控件
      if (state.total <= 0) {
        state.total = 0;
      }

      // 验证分页信息的一致性
      const currentPage = state.queryParams.pageNum;
      const pageSize = state.queryParams.pageSize;
      const totalPages = Math.ceil(state.total / pageSize);

      // 检查数据条数是否符合预期
      const expectedCount = Math.min(pageSize, Math.max(0, state.total - (currentPage - 1) * pageSize));

      // 如果当前页超出范围，自动调整到最后一页
      if (currentPage > totalPages && totalPages > 0) {
        state.queryParams.pageNum = totalPages;
        // 重新请求正确的页码
        setTimeout(() => searchByKeyword(), 100);
        return;
      }

      // 更新筛选选项（使用后端返回的筛选选项）
      updateFilterOptionsFromBackend(responseData);

      // 获取符合条件的数量
      fetchExportCount();

    } else {
      // 非200响应：静默回到第一页；若尚未重试，则在本函数内延迟一次重试（仅一次），避免与当前 finally 的 loading 状态冲突
      const wasNotFirstPage = state.queryParams.pageNum !== 1;
      if (wasNotFirstPage) {
        state.queryParams.pageNum = 1;
      }
      if (!retry) {
        setTimeout(() => searchByKeyword(true), 0);
      }
      return;
    }
  } catch (error) {
    // 异常：静默回到第一页；若尚未重试，则在本函数内立即二次请求（仅一次）
    const wasNotFirstPage = state.queryParams.pageNum !== 1;
    if (wasNotFirstPage) {
      state.queryParams.pageNum = 1;
    }
    if (!retry) {
      setTimeout(() => searchByKeyword(true), 0);
      await searchByKeyword(false);

    }
  }
    finally {
    state.loading = false;
    countLoading.value = false; // 取消数量加载状态
  }
};

// 使用后端返回的筛选选项更新state（推荐方式）
const updateFilterOptionsFromBackend = (responseData) => {
  if (!responseData) return;

  // 处理当前所在地选项 - 已改为使用预定义城市列表，不再从后端获取
  // 当前所在地数据现在使用预定义的城市列表，不需要从后端获取
  state.allCurrentLocations = predefinedCurrentLocations.map(city => city.original);

  // 处理家乡选项 - 已改为使用预定义城市列表，不再从后端获取
  // 家乡数据现在使用预定义的城市列表，不需要从后端获取
  state.allHometowns = predefinedHometowns.map(city => city.original);

  // 处理关系状态选项 - 已改为使用预定义关系状态列表，不再从后端获取
  // 关系状态数据现在使用预定义的关系状态列表，不需要从后端获取
  state.allRelationshipStatuses = predefinedRelationshipStatuses.map(status => status.zh);

  // 处理工作地点选项 - 已改为使用预定义工作地点列表，不再从后端获取
  // 工作地点数据现在使用预定义的工作地点列表，不需要从后端获取
  state.allWorkplaces = predefinedWorkplaces.map(workplace => workplace.original);
};

// 更新筛选选项（当数据变化时）- 保留作为备用方法
const updateFilterOptionsFromCurrentData = () => {
  if (state.contactsList && state.contactsList.length > 0) {
    const currentOptions = extractFilterOptions(state.contactsList);

    // 当前所在地始终使用预定义列表
    state.allCurrentLocations = predefinedCurrentLocations.map(city => city.original);
    // 家乡始终使用预定义列表
    state.allHometowns = predefinedHometowns.map(city => city.original);
    // 关系状态始终使用预定义列表
    state.allRelationshipStatuses = predefinedRelationshipStatuses.map(status => status.zh);
    // 工作地点始终使用预定义列表
    state.allWorkplaces = predefinedWorkplaces.map(workplace => workplace.original);
  }
};





// 数据提取和处理函数
const extractFilterOptions = (contacts) => {
  return {
    currentLocations: [], // 当前所在地不再从联系人数据中提取，返回空数组
    hometowns: [], // 家乡不再从联系人数据中提取，返回空数组
    relationshipStatuses: [], // 关系状态不再从联系人数据中提取，返回空数组
    workplaces: [] // 工作地点不再从联系人数据中提取，返回空数组
  };
};

// 修改初始化地区数据的函数 - 获取更多数据用于筛选选项
const initializeLocationData = async () => {
  if (state.initialized) return; // 防止重复初始化

  try {
    state.loading = true;

    // 获取大量数据来提取完整的筛选选项
    const response = await getFacebookList({
      pageNum: 1,
      pageSize: 10  // 增加数据量以获取更完整的筛选选项
    });

    if (response && response.code === 200) {
      // 处理后端返回的数据格式
      const responseData = response.data && response.data.data ? response.data.data : response.data;
      const contacts = responseData.list || [];

      // 直接使用后端返回的筛选选项，无需前端提取
      // 处理当前所在地选项 - 使用预定义城市列表
      state.allCurrentLocations = predefinedCurrentLocations.map(city => city.original);

      // 处理家乡选项 - 使用预定义城市列表
      state.allHometowns = predefinedHometowns.map(city => city.original);

      // 处理关系状态选项 - 使用预定义关系状态列表
      state.allRelationshipStatuses = predefinedRelationshipStatuses.map(status => status.zh);

      // 处理工作地点选项 - 使用预定义工作地点列表
      state.allWorkplaces = predefinedWorkplaces.map(workplace => workplace.original);
      
      // 设置默认为空（不选中任何选项）
      state.filters.genders = [];
      state.filters.currentLocations = [];
      state.filters.hometowns = [];
      state.filters.relationshipStatuses = [];
      state.filters.workplaces = [];
      state.filters.contactMethods = [];
      
      // 设置全选状态为false
      state.checkAll.gender = false;
      state.checkAll.currentLocation = false;
      state.checkAll.hometown = false;
      state.checkAll.relationshipStatus = false;
      state.checkAll.workplace = false;
      state.checkAll.contactMethod = false;
      
      // 使用返回的数据直接更新列表，避免再次请求
      state.contactsList = contacts.map(contact => ({
        ...contact,
        expanded: false
      }));
      state.total = responseData.total || 0;
      
      // 标记为已初始化
      state.initialized = true;
    } else {
      const msg = (response && (response.msg || response.message || response.data?.msg || response.data?.message)) || '';
      if (msg.includes('余额不足')) {
        if (state.queryParams.pageNum !== 1) {
          state.queryParams.pageNum = 1;
        }
        return;
      }
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('初始化数据失败，请刷新页面重试');
      } else {
        ElMessage.error('Failed to initialize data, please refresh the page and try again');
      }
    }
  } catch (error) {
    try {
      const errMsg = (error && (error.response?.data?.message || error.response?.data?.msg || error.message)) || '';
      if (errMsg.includes('余额不足')) {
        if (state.queryParams.pageNum !== 1) {
          state.queryParams.pageNum = 1;
        }
        return;
      }
    } catch (_) { /* ignore */ }
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('初始化数据失败，请刷新页面重试');
    } else {
      ElMessage.error('Failed to initialize data, please refresh the page and try again');
    }
  } finally {
    state.loading = false;
  }
};

// 修改页面加载时的初始化逻辑
onMounted(() => {
  // 添加翻译
  addTranslation('facebook.update.date', {
    zh: '更新日期',
    en: 'Update Date'
  });
  
  addTranslation('facebook.join.date', {
    zh: '加入日期',
    en: 'Join Date'
  });
  
  addTranslation('facebook.id', {
    zh: '用户账号',
    en: 'Facebook ID'
  });
  
  // 添加符合条件的联系人数量相关翻译
  addTranslation('facebook.matched.count', {
    zh: '符合条件的联系人：',
    en: 'Matched Contacts: '
  });
  
  addTranslation('facebook.matched.count.unit', {
    zh: ' 条',
    en: ' items'
  });
  
  // 添加导出对话框标题翻译
  addTranslation('export.dialog.title', {
    zh: '导出数据',
    en: 'Export Data'
  });
  
  // 添加导出限制提示翻译
  addTranslation('export.max.limit.notice', {
    zh: '最多可导出50000条记录',
    en: 'Maximum export limit is 50,000 records'
  });
  
  // 添加导出弹窗翻译
  addTranslation('export.matched.records', {
    zh: '符合条件的记录数',
    en: 'Matched records'
  });
  
  addTranslation('export.current.balance', {
    zh: '当前导出余额',
    en: 'Current export balance'
  });
  
  addTranslation('export.consumption.notice', {
    zh: '注意: 每导出一条记录将消耗一点导出额度',
    en: 'Note: Each exported record consumes one export quota'
  });
  
  addTranslation('export.enter.count', {
    zh: '请输入要导出的记录数',
    en: 'Please enter the number of records to export'
  });
  
  addTranslation('export.warning.count.exceeded', {
    zh: '导出数量不能超过符合条件的记录数',
    en: 'Export count cannot exceed the matched records'
  });
  
  addTranslation('export.warning.insufficient.balance', {
    zh: '导出余额不足',
    en: 'Insufficient export balance'
  });
  
  addTranslation('export.confirm', {
    zh: '确认导出',
    en: 'Confirm Export'
  });
  
  addTranslation('cancel', {
    zh: '取消',
    en: 'Cancel'
  });
  
  // 添加匹配弹窗翻译
  addTranslation('facebook.match.data', {
    zh: '匹配数据',
    en: 'Match Data'
  });
  
  addTranslation('facebook.match.upload', {
    zh: '上传匹配',
    en: 'Upload Match'
  });
  
  addTranslation('facebook.match.select.file', {
    zh: '请选择匹配方式并上传Excel文件',
    en: 'Please select match type and upload Excel file'
  });
  
  addTranslation('facebook.match.type', {
    zh: '匹配方式',
    en: 'Match Type'
  });
  
  addTranslation('facebook.match.type.1', {
    zh: '工作地点+姓名，匹配邮箱',
    en: 'Company+Name, match email'
  });
  
  addTranslation('facebook.match.type.2', {
    zh: '工作地点+姓名，匹配手机号',
    en: 'Company+Name, match phone'
  });
  
  addTranslation('facebook.match.type.3', {
    zh: '姓名+邮箱，匹配手机号',
    en: 'Name+Email, match phone'
  });
  
  addTranslation('facebook.match.type.4', {
    zh: '手机号+姓名，匹配邮箱',
    en: 'Phone+Name, match email'
  });
  
  addTranslation('facebook.match.upload.file', {
    zh: '上传Excel文件',
    en: 'Upload Excel file'
  });
  
  addTranslation('facebook.match.drag.file', {
    zh: '拖拽文件到此处或',
    en: 'Drag file here or'
  });
  
  addTranslation('facebook.match.click.upload', {
    zh: '点击上传',
    en: 'click to upload'
  });
  
  addTranslation('facebook.match.file.tip', {
    zh: '请上传符合模板的Excel文件，格式为.xlsx',
    en: 'Please upload Excel file in .xlsx format according to the template'
  });
  
  addTranslation('facebook.match.download.template', {
    zh: '下载模板文件',
    en: 'Download template file'
  });
  
  addTranslation('facebook.match.progress', {
    zh: '匹配进度',
    en: 'Matching progress'
  });
  
  addTranslation('facebook.match.result', {
    zh: '匹配结果',
    en: 'Match result'
  });
  
  addTranslation('facebook.match.total', {
    zh: '总数据',
    en: 'Total data'
  });
  
  addTranslation('facebook.match.success', {
    zh: '成功匹配',
    en: 'Successfully matched'
  });
  
  addTranslation('facebook.match.fail', {
    zh: '未匹配',
    en: 'Unmatched'
  });
  
  addTranslation('facebook.match.history', {
    zh: '匹配历史',
    en: 'Match history'
  });
  
  addTranslation('facebook.match.time', {
    zh: '匹配时间',
    en: 'Match time'
  });
  
  addTranslation('facebook.match.type.label', {
    zh: '匹配类型',
    en: 'Match type'
  });
  
  addTranslation('facebook.match.total.records', {
    zh: '总记录数',
    en: 'Total records'
  });
  
  addTranslation('facebook.match.matched.records', {
    zh: '成功匹配数',
    en: 'Successfully matched'
  });
  
  addTranslation('facebook.match.operation', {
    zh: '操作',
    en: 'Operation'
  });
  
  addTranslation('facebook.match.download.result', {
    zh: '下载结果',
    en: 'Download result'
  });
  
  addTranslation('facebook.start.match', {
    zh: '开始匹配',
    en: 'Start Matching'
  });
  
  addTranslation('facebook.match.download', {
    zh: '下载结果',
    en: 'Download Result'
  });
  
  addTranslation('facebook.match.type.unknown', {
    zh: '未知类型',
    en: 'Unknown Type'
  });
  
  // 初始化数据
  initializeLocationData();
  
  // 添加延时获取联系人数量，确保在初始化完成后更新显示的联系人数量
  setTimeout(() => {
    fetchExportCount();
  }, 800);
});

// 修改 updateQueryParams 函数，添加初始化检查
const updateQueryParams = () => {
  if (!state.initialized) return; // 如果未初始化完成，不执行更新
  
  // 准备新的查询参数
  const newParams = { ...state.queryParams };
  
  // 处理性别筛选参数
  if (state.filters.genders.length === 0) {
    newParams.gender = '';
  } else if (state.filters.genders.length === 1) {
    newParams.gender = state.filters.genders[0];
  } else if (state.filters.genders.length === 2) {
    newParams.gender = '';  // 两种性别都选择时发送空字符串，表示不筛选
  }
  
  // 处理当前位置筛选参数
  if (state.filters.currentLocations.length === 0) {
    newParams.currentLocation = '';
  } else if (state.filters.currentLocations.length === state.allCurrentLocations?.length) {
    newParams.currentLocation = ''; // 当所有地区被选中时，使用空字符串代替 'all'
  } else {
    newParams.currentLocation = state.filters.currentLocations.join('、');
  }
  
  // 处理家乡筛选参数
  if (state.filters.hometowns.length === 0) {
    newParams.hometown = '';
  } else if (state.filters.hometowns.length === state.allHometowns?.length) {
    newParams.hometown = ''; // 当所有家乡被选中时，使用空字符串代替 'all'
  } else {
    newParams.hometown = state.filters.hometowns.join('、');
  }
  
  // 处理关系状态筛选参数 - 传输所有语言版本
  if (state.filters.relationshipStatuses.length === 0) {
    newParams.relationshipStatus = '';
  } else if (state.filters.relationshipStatuses.length === predefinedRelationshipStatuses.length) {
    newParams.relationshipStatus = ''; // 当所有关系状态被选中时，使用空字符串
  } else {
    // 获取选中关系状态的所有语言版本
    const allValues = getAllRelationshipStatusValues(state.filters.relationshipStatuses);
    newParams.relationshipStatus = allValues.join('、');
  }
  
  // 处理工作地点筛选参数
  if (state.filters.workplaces.length === 0) {
    newParams.workplace = '';
  } else if (state.filters.workplaces.length === state.allWorkplaces?.length) {
    newParams.workplace = ''; // 当所有工作地点被选中时，使用空字符串
  } else {
    newParams.workplace = state.filters.workplaces.join('、');
  }
  
  // 处理联系方式筛选参数
  if (state.filters.contactMethods.length === 0) {
    newParams.contactMethod = '';
    newParams.email = '';
    newParams.phone = '';
  } else if (state.filters.contactMethods.length === 2) {
    newParams.contactMethod = 'any';
    newParams.email = '';
    newParams.phone = '';
  } else {
    newParams.contactMethod = '';
    newParams.email = state.filters.contactMethods.includes('email') ? 'notempty' : '';
    newParams.phone = state.filters.contactMethods.includes('phone') ? 'notempty' : '';
  }
  
  // 一次性更新所有查询参数
  Object.assign(state.queryParams, newParams);
  
  // 触发防抖的搜索函数
  searchByKeyword();
};

// 重置姓名搜索
const resetNameSearch = () => {
  state.queryParams.name = '';
  state.queryParams.pageNum = 1;
  searchByKeyword();
};

// 重置所有筛选条件
const resetAllFilters = (isFromUserClick = false) => {
  // 重置所有筛选展开状态
  Object.keys(state.expanded).forEach(key => {
    state.expanded[key] = false;
  });
  
  // 重置性别为不选
  state.filters.genders = [];
  state.checkAll.gender = false;
  
  // 重置当前位置为不选
  state.filters.currentLocations = [];
  state.checkAll.currentLocation = false;
  
  // 重置家乡为不选
  state.filters.hometowns = [];
  state.checkAll.hometown = false;
  
  // 重置关系状态为不选
  state.filters.relationshipStatuses = [];
  state.checkAll.relationshipStatus = false;
  
  // 重置工作地点为不选
  state.filters.workplaces = [];
  state.checkAll.workplace = false;
  
  // 重置联系方式为不选
  state.filters.contactMethods = [];
  state.checkAll.contactMethod = false;
  
  // 重置搜索框
  state.queryParams.name = '';
  currentLocationSearch.value = '';
  hometownSearch.value = '';
  relationshipStatusSearch.value = '';
  workplaceSearch.value = '';
  
  // 重置ES搜索结果
  esCurrentLocations.value = [];
  esHometowns.value = [];
  esWorkplaces.value = [];
  
  // 重置分页
  state.queryParams.pageNum = 1;
  
  // 重置列表数据，确保不会有旧数据残留
  state.contactsList = [];
  
  // 获取数据
  searchByKeyword();
  
  // 只有在用户明确点击重置按钮时才显示成功消息
  if (isFromUserClick) {
    ElMessage.success(t('facebook.filter.resetSuccess'));
  }
};

// 获取随机头像
const getRandomAvatar = (id, name) => {
  // 使用姓名作为seed生成一致的头像
  if (name) {
    const seed = name.toLowerCase().replace(/\s/g, '')
    // 为不同用户使用不同的风格，增加多样性
    const styles = ['micah', 'avataaars', 'adventurer', 'bottts', 'personas']
    const style = styles[Math.abs(seed.charCodeAt(0)) % styles.length]
    return `https://api.dicebear.com/7.x/${style}/svg?seed=${seed}`
  }
  
  // 使用卡通风格的头像（备用）
  const avatars = [
    'https://api.dicebear.com/7.x/micah/svg?seed=Felix',
    'https://api.dicebear.com/7.x/avataaars/svg?seed=Aneka',
    'https://api.dicebear.com/7.x/adventurer/svg?seed=Bailey',
    'https://api.dicebear.com/7.x/bottts/svg?seed=Chloe',
    'https://api.dicebear.com/7.x/personas/svg?seed=Dustin'
  ]
  return avatars[id ? Math.abs(id.hashCode()) % avatars.length : 0]
}

// 处理头像加载错误 - 修复函数定义
const handleAvatarError = (e) => {
  // 加载失败时使用另一套卡通头像
  const seed = Math.random().toString(36).substring(2, 8)
  e.target.src = `https://api.dicebear.com/7.x/avataaars/svg?seed=${seed}`
}

// 格式化地点
const formatLocation = (location) => {
  if (!location) return '未知地区'
  return location
}

// 格式化性别 - 支持国际化
const formatGender = (gender) => {
  if (!gender) {
    return currentLanguage.value === 'zh' ? '未知' : 'Unknown'
  }

  // 转换为小写以支持大小写不敏感处理
  const genderLower = gender.toLowerCase().trim()

  // 定义性别映射表，支持多语言和多格式
  const GENDER_MAP = {
    // 英文格式
    'male': { zh: '男', en: 'Male' },
    'female': { zh: '女', en: 'Female' },
    'm': { zh: '男', en: 'Male' },
    'f': { zh: '女', en: 'Female' },
    'man': { zh: '男', en: 'Male' },
    'woman': { zh: '女', en: 'Female' },

    // 印尼语格式
    'laki-laki': { zh: '男', en: 'Male' },
    'perempuan': { zh: '女', en: 'Female' },

    // 中文格式（兼容可能的中文输入）
    '男': { zh: '男', en: 'Male' },
    '女': { zh: '女', en: 'Female' },
    '男性': { zh: '男', en: 'Male' },
    '女性': { zh: '女', en: 'Female' },

    // 其他可能的格式
    'boy': { zh: '男', en: 'Male' },
    'girl': { zh: '女', en: 'Female' },
    'other': { zh: '其他', en: 'Other' },
    'unknown': { zh: '未知', en: 'Unknown' }
  }

  // 查找映射表中的值
  const genderData = GENDER_MAP[genderLower]

  if (genderData) {
    // 根据当前语言返回对应的显示文本
    return currentLanguage.value === 'zh' ? genderData.zh : genderData.en
  }

  // 如果找不到映射值，返回原始值或默认值
  return gender || (currentLanguage.value === 'zh' ? '未知' : 'Unknown')
}


// 格式化电话号码
const formatPhoneNumber = (phone) => {
  if (!phone) return ''
  // 转为字符串并格式化
  const phoneStr = String(phone)
  if (phoneStr.length === 10) {
    return `${phoneStr.substring(0, 3)}-${phoneStr.substring(3, 6)}-${phoneStr.substring(6)}`
  }
  return phoneStr
}

// 切换联系人详情展开/收起
const toggleContactDetails = (contact) => {
  // 如果是要展开详情（从收起状态变为展开状态）
  if (!contact.expanded) {
    // 显示次数消耗确认提示框
    ElMessageBox.confirm(
      t('detail.title.content'),
        t('detail.title.title'),
      {
        confirmButtonText: t('detail.confirm.content'),
        // 1
        cancelButtonText: t('detail.cancel.content'),
        type: 'warning',
        center: true
      }
    ).then(() => {
      // 用户确认后，展开详情
      expandContactDetails(contact);
    }).catch(() => {
      // 用户取消，不做任何操作
    });
  } else {
    // 如果是收起详情，直接执行
    collapseContactDetails(contact);
  }
};

// 展开联系人详情 - 修复数据覆盖问题
const expandContactDetails = async (contact) => {

  try {
    // 1. 设置加载状态
    contact.loading = true;

    // 2. 先更新展开状态，显示加载中
    contact.expanded = true;
    updateContactInList(contact);


    // 3. 调用后端API获取详细信息
    const response = await getFacebookDetailByTableAndId({
      mysqlTable: contact.mysqlTable,
      id: contact.id
    });

    if (response && response.code === 200 && response.data) {
      // 4. 用后端返回的详细数据更新联系人信息
      const detailedData = response.data;

      // 清理和过滤详细数据
      const cleanedDetailedData = cleanAndFilterContactData(detailedData);


      // 合并原有数据和清理后的详细数据，详细数据优先
      // 但保留关键标识符字段，确保记录定位不会出错
      const updatedContact = {
        ...contact,
        ...cleanedDetailedData,
        // 强制保留原有的标识符字段，防止被后端数据覆盖
        mysqlTable: contact.mysqlTable,
        id: contact.id,
        // 智能处理facebookId字段：优先使用后端返回的数据，如果没有则保留原有数据
        facebookId: cleanedDetailedData.facebookId || contact.facebookId,
        expanded: true,
        loading: false,
        hasDetailedData: true // 标记已获取详细数据
      };

      // 5. 更新联系人列表中的数据
      updateContactInList(updatedContact);

    } else {
      if(getCurrentLanguage() === 'zh') {
        ElMessage.error('获取详细信息失败，请稍后重试');
      } else {
        ElMessage.error('Failed to get detailed data, please try again later');
      }
      contact.loading = false;
      updateContactInList(contact);
    }

  } catch (error) {
    if(getCurrentLanguage() === 'zh') {
      ElMessage.error('获取详细信息出错，请稍后重试');
    } else {
      ElMessage.error('Failed to get detailed data, please try again later');
    }
    contact.loading = false;
    updateContactInList(contact);
  }
};

// 清理和过滤联系人数据
const cleanAndFilterContactData = (data) => {
  if (!data || typeof data !== 'object') {
    return {};
  }

  // 定义需要排除的内部字段
  const excludeFields = ['mysqlTable', 'id'];

  // 清理后的数据对象
  const cleanedData = {};

  // 遍历所有字段
  Object.keys(data).forEach(key => {
    const value = data[key];

    // 跳过内部字段
    if (excludeFields.includes(key)) {
      return;
    }

    // 跳过空值字段
    if (isEmptyValue(value)) {
      return;
    }

    // 保留有效字段
    cleanedData[key] = value;
  });

  return cleanedData;
};

// 检查字段值是否有效（用于模板中的v-if条件）
const hasValidValue = (value) => {
  return value !== null &&
         value !== undefined &&
         value !== '' &&
         (typeof value !== 'string' || value.trim() !== '') &&
         value !== 'null' &&
         value !== 'undefined';
};

// 获取额外字段（排除已在模板中显示的字段）
const getAdditionalFields = (contact) => {
  if (!contact || typeof contact !== 'object') {
    return {};
  }

  // 定义已在模板中显示的字段
  const displayedFields = [
    'fullName', 'firstName', 'lastName', 'gender', 'currentLocation',
    'hometown', 'relationshipStatus', 'workplace', 'email', 'phoneNumber',
    'facebookId', 'date', 'joinDate', 'expanded', 'loading', 'hasDetailedData',
    'mysqlTable', 'id' // 内部字段也要排除
  ];



  // 获取额外字段
  const additionalFields = {};

  Object.keys(contact).forEach(key => {
    // 跳过已显示的字段
    if (displayedFields.includes(key)) {
      return;
    }

    // 跳过空值字段
    if (isEmptyValue(contact[key])) {
      return;
    }

    // 保留额外字段
    additionalFields[key] = contact[key];
  });

  return additionalFields;
};

// 获取字段显示标签
const getFieldLabel = (fieldKey) => {
  // 字段标签映射
  const fieldLabels = {
    age: '年龄',
    education: '教育背景',
    occupation: '职业',
    interests: '兴趣爱好',
    languages: '语言',
    website: '网站',
    bio: '个人简介',
    company: '公司',
    school: '学校',
    location: '位置',
    birthday: '生日',
    anniversary: '纪念日',
    religion: '宗教',
    political: '政治观点',
    quotes: '座右铭',
    about: '关于',
    favoriteTeams: '喜欢的团队',
    favoriteAthletes: '喜欢的运动员',
    inspirationalPeople: '崇拜的人',
    familyMembers: '家庭成员',
    lifeEvents: '人生大事',
    // 可以根据需要添加更多字段映射
  };

  // 返回映射的标签，如果没有映射则使用原字段名（首字母大写）
  return fieldLabels[fieldKey] || fieldKey.charAt(0).toUpperCase() + fieldKey.slice(1);
};

// 格式化字段值
const formatFieldValue = (fieldKey, value) => {
  if (!value) return '';

  // 根据字段类型进行特殊格式化
  switch (fieldKey) {
    case 'birthday':
    case 'anniversary':
      return formatDatetime(value);
    case 'age':
      return value + '岁';
    case 'website':
      return value; // 可以考虑添加链接格式
    default:
      return String(value);
  }
};

// 公共的空值检查函数
const isEmptyValue = (value) => {
  return value === null ||
         value === undefined ||
         value === '' ||
         (typeof value === 'string' && value.trim() === '') ||
         value === 'null' ||
         value === 'undefined';
};

// 更新联系人列表中的数据（辅助函数）- 修复数据覆盖问题
const updateContactInList = (updatedContact) => {

  // 使用 mysqlTable + id 的组合作为唯一标识符进行精确匹配
  const index = state.contactsList.findIndex(item => {
    // 优先使用 mysqlTable + id 组合进行精确匹配
    if (item.mysqlTable && item.id && updatedContact.mysqlTable && updatedContact.id) {
      const isMatch = item.mysqlTable === updatedContact.mysqlTable && item.id === updatedContact.id;
      return isMatch;
    }

    // 备用匹配策略：使用 facebookId
    if (item.facebookId && updatedContact.facebookId) {
      const isMatch = item.facebookId === updatedContact.facebookId;
      return isMatch;
    }

    return false;
  });

  if (index !== -1) {

    // 克隆整个contactsList，确保Vue能检测到变化
    const updatedList = [...state.contactsList];
    updatedList[index] = { ...updatedContact };
    state.contactsList = updatedList;

  } else {
    if(getCurrentLanguage() === 'zh') {
      ElMessage.error('更新失败')
    } else {
      ElMessage.error('Failed to update')
    }
  }
};

// 收起联系人详情 - 修复数据覆盖问题
const collapseContactDetails = (contact) => {

  // 1. 修改当前联系人的展开状态
  contact.expanded = false;

  // 2. 使用精确匹配策略找到对应联系人并更新
  const index = state.contactsList.findIndex(item => {
    // 优先使用 mysqlTable + id 组合进行精确匹配
    if (item.mysqlTable && item.id && contact.mysqlTable && contact.id) {
      return item.mysqlTable === contact.mysqlTable && item.id === contact.id;
    }

    // 备用匹配策略：使用 facebookId
    if (item.facebookId && contact.facebookId) {
      return item.facebookId === contact.facebookId;
    }

    return false;
  });

  if (index !== -1) {

    // 3. 克隆整个contactsList，确保Vue能检测到变化
    const updatedList = [...state.contactsList];
    updatedList[index] = { ...updatedList[index], expanded: false };
    state.contactsList = updatedList;

  } else {

  }
};



// 处理导出
const handleExport = async () => {
  exportLoading.value = true
  try {
    // 先获取符合条件的记录数量
    await fetchExportCount()
    
    // 再获取用户余额
    await fetchUserBalance()
    
    // 显示导出对话框
    exportDialogVisible.value = true
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('准备导出失败，请稍后重试')
    } else {
      ElMessage.error('Failed to prepare export, please try again later')
    }
  } finally {
    exportLoading.value = false
  }
};

// 获取符合条件的记录数量
const fetchExportCount = async () => {
  try {
    // 构建和搜索功能一致的查询参数，使用后端 FacebookQueryDTO 期望的字段名
    const searchParams = {
      // 基本搜索参数
      name: state.queryParams.name || '',
      pageNum: state.queryParams.pageNum,
      pageSize: state.queryParams.pageSize,

      // 筛选参数 - 使用后端期望的字段名
      gender: buildGenderParam(state.filters.genders),

      // 当前位置筛选参数 - 支持多选
      currentLocation: buildMultiSelectParam(
        state.filters.currentLocations,
        state.allCurrentLocations,
        '当前所在地'
      ),

      // 家乡筛选参数 - 支持多选
      hometown: buildMultiSelectParam(
        state.filters.hometowns,
        state.allHometowns,
        '家乡'
      ),

      // 关系状态筛选参数 - 支持多选多语言
      relationshipStatus: buildRelationshipStatusParam(
        state.filters.relationshipStatuses,
        state.allRelationshipStatuses,
        '关系状态'
      ),

      // 工作地点筛选参数 - 支持多选
      workplace: buildMultiSelectParam(
        state.filters.workplaces,
        state.allWorkplaces,
        '工作地点'
      ),

      // 联系方式筛选参数
      contactMethod: state.filters.contactMethods.length === 0 ? '' :
                    state.filters.contactMethods.length === 2 ? 'any' :
                    state.filters.contactMethods[0]
    };
    const response = await getFacebookCount(searchParams);
    
    if (response.code === 200) {
      const count = response.data.count || 0;
      
      totalMatchCount.value = count > 50000 ? 50000 : count;
      exportCount.value = Math.min(totalMatchCount.value, 1000); // 默认设置为1000条或总数
      
      // 更新显示的数量，限制显示到10000条
      displayedCount.value = count > 10000 ? '10,000+' : formatNumber(count);
      return count;
    } else {
      if(getCurrentLanguage() === 'zh') {
        ElMessage.error(response.msg || '获取记录数量失败');
      } else {
        ElMessage.error('Failed to get record count');
      }
      return 0;
    }
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('获取记录数量失败，请稍后重试');
    } else {
      ElMessage.error('Failed to get record count, please try again later');
    }
    return 0;
  }
};

// 格式化数字的函数
const formatNumber = (num) => {
  if (num === null || num === undefined) return '0';
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};

// 获取用户余额
const fetchUserBalance = async () => {
  try {
    const response = await getUserBalanceInfo();
    if (response.code === 200 && response.data) {
      userBalance.value = response.data;
      return response.data;
    } else {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error(response.msg || '获取余额信息失败');
      } else {
        ElMessage.error('Failed to get balance info');
      }
      return { exportQuotaRemaining: 0 };
    }
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('获取余额信息失败，请稍后重试');
    } else {
      ElMessage.error('Failed to get balance info, please try again later');
    }
    return { exportQuotaRemaining: 0 };
  }
};

// 执行导出操作
const doExport = async () => {
  // 检查导出数量
  if (isExportCountExceeded.value) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error(`导出数量不能超过符合条件的记录数 ${totalMatchCount.value}`);
    } else {
      ElMessage.error(`Export count cannot exceed the number of records that meet the conditions ${totalMatchCount.value}`);
    }
    return;
  }
  
  // 检查导出上限 - 不显示特定错误消息，但仍执行限制
  if (isExportLimitExceeded.value) {
    // 将超出50000限制时的错误提示合并到"超过符合条件的记录数"
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('导出数量不能超过符合条件的记录数');
    } else {
      ElMessage.error('Export count cannot exceed the number of records that meet the conditions');
    }
    return;
  }
  
  // 检查余额
  if (isBalanceInsufficient.value) {
    if(getCurrentLanguage() === 'zh') {
      ElMessage.error(`导出余额不足，当前余额: ${userBalance.value.exportQuotaRemaining}`);
    } else {
      ElMessage.error(`Insufficient balance, current balance: ${userBalance.value.exportQuotaRemaining}`);
    }
    return;
  }
  
  // 确保导出数量是有效的数字
  if (!exportCount.value || isNaN(Number(exportCount.value)) || Number(exportCount.value) <= 0) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('请输入有效的导出数量');
    } else {
      ElMessage.error('Please enter a valid export count');
    }
    return;
  }
  
  exportLoading.value = true;
  try {
    // 构建和搜索功能一致的查询参数，使用后端 FacebookQueryDTO 期望的字段名
    const exportParams = {
      // 基本搜索参数
      name: state.queryParams.name || '',
      pageNum: state.queryParams.pageNum,
      pageSize: state.queryParams.pageSize,
      // 添加导出数量
      exportCount: Number(exportCount.value),

      // 筛选参数 - 使用后端期望的字段名
      gender: buildGenderParam(state.filters.genders),

      // 当前位置筛选参数 - 支持多选
      currentLocation: buildMultiSelectParam(
        state.filters.currentLocations,
        state.allCurrentLocations,
        '当前所在地'
      ),

      // 家乡筛选参数 - 支持多选
      hometown: buildMultiSelectParam(
        state.filters.hometowns,
        state.allHometowns,
        '家乡'
      ),

      // 关系状态筛选参数 - 支持多选多语言
      relationshipStatus: buildRelationshipStatusParam(
        state.filters.relationshipStatuses,
        state.allRelationshipStatuses,
        '关系状态'
      ),

      // 工作地点筛选参数 - 支持多选
      workplace: buildMultiSelectParam(
        state.filters.workplaces,
        state.allWorkplaces,
        '工作地点'
      ),

      // 联系方式筛选参数
      contactMethod: state.filters.contactMethods.length === 0 ? '' :
                    state.filters.contactMethods.length === 2 ? 'any' :
                    state.filters.contactMethods[0]
    };
    if (getCurrentLanguage() === 'zh') {
      ElMessage.info('正在准备导出数据，请稍候...');
    } else {
      ElMessage.info('Preparing data for export, please wait...');
    }
    
    // 发送请求
    const response = await exportFacebookData(exportParams);
    if (!response || !response.data) {
      if(getCurrentLanguage() === 'zh') {
        throw new Error('导出失败');
      } else {
        throw new Error('Export failed');
      }
    }
    
    if (!(response.data instanceof Blob)) {
      if(getCurrentLanguage() === 'zh') {
        throw new Error('导出失败');
      } else {
        throw new Error('Export failed');
      }    }
    
    // 获取Content-Type
    const contentType = response.headers && response.headers['content-type'] 
      ? response.headers['content-type'] 
      : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    
    // 检查是否是错误响应
    if (contentType.includes('json')) {
      // 可能是错误响应，尝试解析
      const reader = new FileReader();
      
      // 使用Promise包装FileReader
      const readJsonResponse = new Promise((resolve, reject) => {
        reader.onload = function() {
          try {
            const result = reader.result;
            const errorResponse = JSON.parse(result);
            resolve(errorResponse);
          } catch (e) {
            if(getCurrentLanguage() === 'zh') {
              reject(new Error('导出失败'));
            } else {
              reject(new Error('Export failed'));
            }
          }
        };
        reader.onerror = function(e) {
          if (getCurrentLanguage() === 'zh'){
            reject(new Error('导出失败'));
          } else {
            reject(new Error('Export failed'));
          }
        };
      });
      
      reader.readAsText(response.data);
      
      try {
        const errorData = await readJsonResponse;
        // 显示具体的错误信息
        const errorMessage = errorData.msg || errorData.message || '未知错误';
        if (getCurrentLanguage() === 'zh'){
          ElMessage.error(`导出失败：${errorMessage}`);
        } else {
          ElMessage.error(`Export failed`);
        }

        // 如果错误与参数相关，可能需要提示用户修改导出数量
        if (errorMessage.includes('exportCount') || errorMessage.includes('导出数量')) {
          if (getCurrentLanguage() === 'zh'){
            ElMessage.warning('请检查导出数量是否正确设置');
          } else {
            ElMessage.warning('Please check if the export count is correctly set');
          }
        }
        
        return;
      } catch (e) {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error(e.message || '导出失败：无法识别的错误');
        } else {
          ElMessage.error('Export failed');
        }
        return;
      }
    }
    
    // 创建Blob对象
    const blob = new Blob([response.data], { type: contentType });
    
    // 获取文件名
    let fileName = 'facebook_users.xlsx';
    const disposition = response.headers && response.headers['content-disposition'];
    if (disposition && disposition.includes('filename=')) {
      const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
      const matches = filenameRegex.exec(disposition);
      if (matches != null && matches[1]) {
        fileName = matches[1].replace(/['"]/g, '');
        try {
          fileName = decodeURIComponent(fileName);
        } catch (e) {
        }
      }
    }
    
    // 下载文件
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    // 关闭导出对话框
    exportDialogVisible.value = false;
    
    // 更新用户余额
    await fetchUserBalance();
    
    // 记录导出次数
    let key = 'exportCount_facebook';
    let count = parseInt(localStorage.getItem(key) || '0');
    localStorage.setItem(key, count + 1);

    if (getCurrentLanguage() === 'zh') {
      ElMessage.success('导出成功');
    } else {
      ElMessage.success('Export successful');
    }
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('导出失败，请稍后重试');
    } else {
      ElMessage.error('Export failed, please try again later');
    }
  } finally {
    exportLoading.value = false;
  }
};



// 确认添加到线索
const submitAddToLeads = async () => {
  try {
    state.loading = true
    
    const res = await addToLeads(leadForm.contactId, leadForm.remarks)
    
    if (res && res.code === 200) {
      if(getCurrentLanguage() === 'zh') {
        ElMessage.success('添加成功')
      } else {
        ElMessage.success('Added successfully')
      }
      addLeadDialog.value = false
      // 重置表单
      leadForm.contactId = ''
      leadForm.remarks = ''
    } else {
      if(getCurrentLanguage() === 'zh') {
        ElMessage.error('添加失败: ' + (res.message || '未知错误'))
      } else {
        ElMessage.error('Failed to add')
      }
    }
  } catch (error) {
    if(getCurrentLanguage() === 'zh') {
      ElMessage.error('添加失败: ' + (error.message || '未知错误'))
    } else {
      ElMessage.error('Failed to add')
    }
  } finally {
    state.loading = false
  }
}

// String.prototype.hashCode 辅助函数
String.prototype.hashCode = function() {
  let hash = 0
  for (let i = 0; i < this.length; i++) {
    const char = this.charCodeAt(i)
    hash = ((hash << 5) - hash) + char
    hash = hash & hash // Convert to 32bit integer
  }
  return hash
}

// 页面加载时获取数据
onMounted(() => {
  initializeLocationData();
});

// 修改筛选条件的处理函数
const handleGenderCheckAllChange = (val) => {
  state.filters.genders = val ? ['M', 'F'] : [];
  state.checkAll.gender = val;
  state.queryParams.pageNum = 1; // 重置页码
  handleFilterChange();
};

const handleGenderChange = () => {
  // 检查是否所有性别（M和F）都被选中
  state.checkAll.gender = state.filters.genders.includes('M') && state.filters.genders.includes('F');
  
  // 重置页码到第一页
  state.queryParams.pageNum = 1;
  
  // 手动清空当前列表，确保不会有旧数据残留
  state.contactsList = [];
  
  // 调用筛选变化处理函数
  handleFilterChange();
};

const handleCurrentLocationCheckAllChange = (val) => {
  state.filters.currentLocations = val ? predefinedCurrentLocations.map(city => city.original) : [];
  state.checkAll.currentLocation = val;
  state.queryParams.pageNum = 1; // 重置页码
  handleFilterChange();
};

const handleCurrentLocationItemChange = () => {
  // 当有项被选中时，从ES结果中移除已选中项，避免重复显示
  if (state.filters.currentLocations.length > 0 && esCurrentLocations.value.length > 0) {
    esCurrentLocations.value = esCurrentLocations.value.filter(
      location => !state.filters.currentLocations.includes(location)
    );
  }
  
  const allPredefinedOriginals = predefinedCurrentLocations.map(city => city.original);
  state.checkAll.currentLocation = allPredefinedOriginals.length > 0 &&
                           state.filters.currentLocations.length === allPredefinedOriginals.length;
  state.queryParams.pageNum = 1; // 重置页码
  handleFilterChange();
};

const handleContactMethodCheckAllChange = (val) => {
  state.filters.contactMethods = val ? ['email', 'phone'] : [];
  state.checkAll.contactMethod = val;
  state.queryParams.pageNum = 1; // 重置页码
  handleFilterChange();
};

const handleContactMethodChange = () => {
  state.checkAll.contactMethod = state.filters.contactMethods.length === 2;
  state.queryParams.pageNum = 1; // 重置页码
  handleFilterChange();
};

// 切换筛选面板显示状态
const toggleFilter = (filterName) => {
  state.expanded[filterName] = !state.expanded[filterName];
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  if (size && size > 0) {
    state.queryParams.pageSize = size;
    state.queryParams.pageNum = 1; // 重置到第一页
    searchByKeyword();
  } else {
  }
};

// 处理页码变化
const handleCurrentChange = (page) => {
  if (page && page > 0) {
    // 验证页码是否超出范围
    const maxPage = Math.ceil(state.total / state.queryParams.pageSize);
    if (maxPage > 0 && page > maxPage) {
      page = maxPage;
    }

    state.queryParams.pageNum = page;
    searchByKeyword();
  } else {
  }
};



// 新增：切换卡片展开状态
const toggleCardExpansion = (contactId) => {
  state.expandedCards[contactId] = !state.expandedCards[contactId];
};

// 优化筛选条件变化的处理
const handleFilterChange = debounce(() => {
  if (!state.initialized) return;
  
  // 每次筛选条件变化时清空列表，确保完全刷新
  state.contactsList = [];
  
  // 更新查询参数并执行搜索
  updateQueryParams();
}, 500);

// 导出相关的状态
const exportLoading = ref(false)
const exportDialogVisible = ref(false)
const totalMatchCount = ref(0)
const exportCount = ref(0)
const userBalance = ref({
  exportQuotaRemaining: 0
})

// 添加符合条件的数量显示相关变量
const displayedCount = ref(0)
const countLoading = ref(false)

// 导出相关的计算属性
const isExportCountExceeded = computed(() => {
  return exportCount.value > totalMatchCount.value
})

const isBalanceInsufficient = computed(() => {
  return exportCount.value > userBalance.value.exportQuotaRemaining
})

const isExportLimitExceeded = computed(() => {
  return exportCount.value > 50000
})

// 获取全名
const getFullName = (contact) => {
  if (contact.firstName && contact.lastName) {
    return `${contact.firstName} ${contact.lastName}`;
  } else if (contact.firstName) {
    return contact.firstName;
  } else if (contact.lastName) {
    return contact.lastName;
  } else {
    return '未知用户';
  }
};

// 获取名字首字母
const getNameInitial = (contact) => {
  if (contact.firstName) {
    return contact.firstName.charAt(0).toUpperCase();
  } else if (contact.lastName) {
    return contact.lastName.charAt(0).toUpperCase();
  } else {
    return 'U';
  }
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';

  const date = new Date(dateTime);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
};

// 格式化日期时间（模板中使用的函数名）
const formatDatetime = (dateTime) => {
  return formatDateTime(dateTime);
};

// 获取Facebook个人资料页面URL
const getFacebookProfileUrl = (facebookId) => {
  if (!facebookId) return '';
  return `https://www.facebook.com/friends/requests/?profile_id=${facebookId}`;
};

// 复制内容到剪贴板
const copyToClipboard = (text) => {
  navigator.clipboard.writeText(text)
    .then(() => {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.success('链接已复制到剪贴板');
      } else {
        ElMessage.success('Link copied to clipboard');
      }
    })
    .catch(() => {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('复制失败，请手动复制');
      } else {
        ElMessage.error('Copy failed, please manually copy');
      }
    });
};

// 根据搜索关键词过滤当前位置列表 - 使用预定义城市列表
const filteredCurrentLocations = computed(() => {

  // 创建一个映射，用于快速查找已选中的项
  const selectedMap = {};
  if (state.filters.currentLocations && state.filters.currentLocations.length > 0) {
    state.filters.currentLocations.forEach(item => {
      selectedMap[item] = true;
    });
  }

  // 先获取所有已选中的项对应的预定义城市
  const selectedPredefined = predefinedCurrentLocations.filter(city => 
    selectedMap[city.original]
  );

  // 如果没有搜索词，返回预定义列表
  if (!currentLocationSearch.value || currentLocationSearch.value.trim() === '') {
    return selectedPredefined.length > 0 
      ? [...selectedPredefined, ...predefinedCurrentLocations.filter(city => !selectedMap[city.original])]
      : predefinedCurrentLocations;
  }

  const searchTerm = currentLocationSearch.value.toLowerCase().trim();
  // 过滤出匹配搜索词的预定义城市
  const filtered = predefinedCurrentLocations.filter(city => {
    // 如果已被选中，不需要再过滤
    if (selectedMap[city.original]) return false;
    
    // 支持中英文搜索
    return city.zh.toLowerCase().includes(searchTerm) ||
           city.en.toLowerCase().includes(searchTerm) ||
           city.original.toLowerCase().includes(searchTerm);
  });

  // 返回的结果：已选中的项 + 符合搜索条件的项
  const result = [...selectedPredefined, ...filtered];
  return result;
});

// 根据搜索关键词过滤家乡列表 - 使用预定义城市列表
const filteredHometowns = computed(() => {

  // 创建一个映射，用于快速查找已选中的项
  const selectedMap = {};
  if (state.filters.hometowns && state.filters.hometowns.length > 0) {
    state.filters.hometowns.forEach(item => {
      selectedMap[item] = true;
    });
  }

  // 先获取所有已选中的项对应的预定义城市
  const selectedPredefined = predefinedHometowns.filter(city => 
    selectedMap[city.original]
  );

  // 如果没有搜索词，返回预定义列表
  if (!hometownSearch.value || hometownSearch.value.trim() === '') {
    return selectedPredefined.length > 0 
      ? [...selectedPredefined, ...predefinedHometowns.filter(city => !selectedMap[city.original])]
      : predefinedHometowns;
  }

  const searchTerm = hometownSearch.value.toLowerCase().trim();
  // 过滤出匹配搜索词的预定义城市
  const filtered = predefinedHometowns.filter(city => {
    // 如果已被选中，不需要再过滤
    if (selectedMap[city.original]) return false;
    
    // 支持中英文搜索
    return city.zh.toLowerCase().includes(searchTerm) ||
           city.en.toLowerCase().includes(searchTerm) ||
           city.original.toLowerCase().includes(searchTerm);
  });

  // 返回的结果：已选中的项 + 符合搜索条件的项
  const result = [...selectedPredefined, ...filtered];
  return result;
});

// 根据搜索关键词过滤关系状态列表 - 使用预定义关系状态列表
const filteredRelationshipStatuses = computed(() => {

  if (!relationshipStatusSearch.value || relationshipStatusSearch.value.trim() === '') {
    return predefinedRelationshipStatuses;
  }

  const searchTerm = relationshipStatusSearch.value.toLowerCase().trim();
  const filtered = predefinedRelationshipStatuses.filter(status => {
    // 支持中英文搜索，以及所有原始值搜索
    return status.zh.toLowerCase().includes(searchTerm) ||
           status.en.toLowerCase().includes(searchTerm) ||
           status.original.some(orig => orig.toLowerCase().includes(searchTerm));
  });

  return filtered;
});

// 根据搜索关键词过滤工作地点列表 - 使用预定义工作地点列表
const filteredWorkplaces = computed(() => {

  // 创建一个映射，用于快速查找已选中的项
  const selectedMap = {};
  if (state.filters.workplaces && state.filters.workplaces.length > 0) {
    state.filters.workplaces.forEach(item => {
      selectedMap[item] = true;
    });
  }

  // 先获取所有已选中的项对应的预定义工作地点
  const selectedPredefined = predefinedWorkplaces.filter(workplace => 
    selectedMap[workplace.original]
  );

  // 如果没有搜索词，返回预定义列表
  if (!workplaceSearch.value || workplaceSearch.value.trim() === '') {
    return selectedPredefined.length > 0 
      ? [...selectedPredefined, ...predefinedWorkplaces.filter(workplace => !selectedMap[workplace.original])]
      : predefinedWorkplaces;
  }

  const searchTerm = workplaceSearch.value.toLowerCase().trim();
  // 过滤出匹配搜索词的预定义工作地点
  const filtered = predefinedWorkplaces.filter(workplace => {
    // 如果已被选中，不需要再过滤
    if (selectedMap[workplace.original]) return false;
    
    // 支持中英文搜索
    return workplace.zh.toLowerCase().includes(searchTerm) ||
           workplace.en.toLowerCase().includes(searchTerm) ||
           workplace.original.toLowerCase().includes(searchTerm);
  });

  // 返回的结果：已选中的项 + 符合搜索条件的项
  const result = [...selectedPredefined, ...filtered];
  return result;
});

// 从当前页面数据中动态提取筛选选项
const dynamicFilterOptions = computed(() => {
  if (!state.contactsList || state.contactsList.length === 0) {
    return {
      currentLocations: [],
      hometowns: [],
      relationshipStatuses: [],
      workplaces: []
    };
  }

  return extractFilterOptions(state.contactsList);
});

// 合并初始筛选选项和当前页面数据的筛选选项
const mergedFilterOptions = computed(() => {
  // 获取初始筛选选项（从大量数据中提取）
  const initial = {
    currentLocations: predefinedCurrentLocations.map(city => city.original), // 当前所在地始终使用预定义列表
    hometowns: predefinedHometowns.map(city => city.original), // 家乡始终使用预定义列表
    relationshipStatuses: predefinedRelationshipStatuses.map(status => status.zh), // 关系状态始终使用预定义列表
    workplaces: predefinedWorkplaces.map(workplace => workplace.original) // 工作地点始终使用预定义列表
  };

  // 获取当前页面数据的筛选选项
  const current = dynamicFilterOptions.value;

  // 合并并去重，保持排序
  return {
    currentLocations: predefinedCurrentLocations.map(city => city.original), // 当前所在地始终使用预定义列表，不合并
    hometowns: predefinedHometowns.map(city => city.original), // 家乡始终使用预定义列表，不合并
    relationshipStatuses: predefinedRelationshipStatuses.map(status => status.zh), // 关系状态始终使用预定义列表，不合并
    workplaces: predefinedWorkplaces.map(workplace => workplace.original) // 工作地点始终使用预定义列表，不合并
  };
});

// 验证筛选数据是否正确加载
const verifyFilterData = () => {
  const merged = mergedFilterOptions.value;

};

// 家乡筛选处理函数
const handleHometownCheckAllChange = (val) => {
  state.filters.hometowns = val ? predefinedHometowns.map(city => city.original) : [];
  state.checkAll.hometown = val;
  state.queryParams.pageNum = 1; // 重置页码
  handleFilterChange();
};

const handleHometownItemChange = () => {
  // 当有项被选中时，从ES结果中移除已选中项，避免重复显示
  if (state.filters.hometowns.length > 0 && esHometowns.value.length > 0) {
    esHometowns.value = esHometowns.value.filter(
      hometown => !state.filters.hometowns.includes(hometown)
    );
  }
  
  const allPredefinedOriginals = predefinedHometowns.map(city => city.original);
  state.checkAll.hometown = allPredefinedOriginals.length > 0 &&
                         state.filters.hometowns.length === allPredefinedOriginals.length;
  state.queryParams.pageNum = 1; // 重置页码
  handleFilterChange();
};

// 关系状态筛选处理函数
const handleRelationshipStatusCheckAllChange = (val) => {
  state.filters.relationshipStatuses = val ? predefinedRelationshipStatuses.map(status => status.zh) : [];
  state.checkAll.relationshipStatus = val;
  state.queryParams.pageNum = 1; // 重置页码
  handleFilterChange();
};

const handleRelationshipStatusItemChange = () => {
  const allPredefinedZhValues = predefinedRelationshipStatuses.map(status => status.zh);
  state.checkAll.relationshipStatus = allPredefinedZhValues.length > 0 &&
                                   state.filters.relationshipStatuses.length === allPredefinedZhValues.length;
  state.queryParams.pageNum = 1; // 重置页码
  handleFilterChange();
};

// 工作地点筛选处理函数
const handleWorkplaceCheckAllChange = (val) => {
  state.filters.workplaces = val ? predefinedWorkplaces.map(workplace => workplace.original) : [];
  state.checkAll.workplace = val;
  state.queryParams.pageNum = 1; // 重置页码
  handleFilterChange();
};

const handleWorkplaceItemChange = () => {
  // 当有项被选中时，从ES结果中移除已选中项，避免重复显示
  if (state.filters.workplaces.length > 0 && esWorkplaces.value.length > 0) {
    esWorkplaces.value = esWorkplaces.value.filter(
      workplace => !state.filters.workplaces.includes(workplace)
    );
  }
  
  const allPredefinedOriginals = predefinedWorkplaces.map(workplace => workplace.original);
  state.checkAll.workplace = allPredefinedOriginals.length > 0 &&
                          state.filters.workplaces.length === allPredefinedOriginals.length;
  state.queryParams.pageNum = 1; // 重置页码
  handleFilterChange();
};

// 匹配相关的状态
const matchLoading = ref(false)
const matchDialogVisible = ref(false)
const matchProgress = ref(0)
const matchResult = ref({ total: 0, matched: 0, unmatched: 0 })
const matchResultFile = ref(null)
const matchType = ref(1)
const fileList = ref([])
const fileSelected = ref(false)
const uploadedFile = ref(null)
const matchProgressInterval = ref(null)
const activeMatchTab = ref('upload')

// 匹配历史记录相关
const matchRecords = ref([])
const historyLoading = ref(false)
const historyPage = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 加载匹配历史记录
const loadMatchRecords = async () => {
  if (historyLoading.value) return;
  
  historyLoading.value = true;
  try {
    const response = await getMatchRecords({
      pageNum: historyPage.current,
      pageSize: historyPage.size
    });
    
    if (response && response.code === 200) {
      const records = response.data.records || [];
      matchRecords.value = records;
      historyPage.total = response.data.total || 0;
    } else {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error(response.msg || '获取匹配历史记录失败');
      } else {
        ElMessage.error('Failed to get match history records');
      }
    }
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('获取匹配历史记录失败，请重试');
    } else {
      ElMessage.error('Failed to get match history records, please try again');
    }
  } finally {
    historyLoading.value = false;
  }
};

// 匹配记录分页处理
const handleHistorySizeChange = (size) => {
  historyPage.size = size;
  historyPage.current = 1;
  loadMatchRecords();
};

const handleHistoryCurrentChange = (page) => {
  historyPage.current = page;
  loadMatchRecords();
};

// 获取匹配类型文本
const getMatchTypeText = (matchType) => {
  switch (matchType) {
    case 1:
      return t('facebook.match.type.1');
    case 2:
      return t('facebook.match.type.2');
    case 3:
      return t('facebook.match.type.3');
    case 4:
      return t('facebook.match.type.4');
    default:
      return t('facebook.match.type.unknown');
  }
};

// 下载历史匹配结果
const downloadHistoryResult = (recordId) => {
  try {
    // 构建下载链接
    const downloadUrl = `/api/facebook/download-history-result?recordId=${recordId}`;

    if (getCurrentLanguage() === 'zh') {
      ElMessage.info('准备下载文件，请稍候...');
    } else{
      ElMessage.info('Preparing to download file, please wait...');
    }
    
    // 使用XMLHttpRequest而不是fetch，确保正确传递认证信息
    const xhr = new XMLHttpRequest();
    xhr.open('GET', downloadUrl, true);
    xhr.responseType = 'blob';
    xhr.withCredentials = true; // 确保发送认证信息
    
    // 从localStorage获取token并添加到请求头
    const token = localStorage.getItem('token');
    if (token) {
      xhr.setRequestHeader('Authorization', `Bearer ${token}`);
    }
    
    xhr.onload = function() {
      if (xhr.status === 200) {
        // 获取文件名
        let filename = '匹配结果.xlsx';
        const disposition = xhr.getResponseHeader('content-disposition');
        if (disposition && disposition.indexOf('filename=') !== -1) {
          const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
          const matches = filenameRegex.exec(disposition);
          if (matches != null && matches[1]) {
            filename = matches[1].replace(/['"]/g, '');
          }
        }
        
        // 创建blob链接并下载
        const blob = new Blob([xhr.response], { 
          type: xhr.getResponseHeader('content-type') || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        
        // 清理
        setTimeout(() => {
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
        }, 100);

        if (getCurrentLanguage() === 'zh') {
          ElMessage.success('下载成功');
        } else {
          ElMessage.success('Download successful');
        }
      } else {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error(`下载失败: ${xhr.status} ${xhr.statusText}`);
        } else {
          ElMessage.error(`Download failed`);
        }
      }
    };
    
    xhr.onerror = function() {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('下载失败，网络连接错误');
      } else {
        ElMessage.error('Download failed, network connection error');
      }
    };
    
    xhr.send();
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('下载历史匹配结果失败，请重试');
    } else {
      ElMessage.error('Failed to download match result, please try again');
    }
  }
};

// 处理匹配按钮点击
const handleMatch = () => {
  // 重置匹配状态
  matchDialogVisible.value = true
  activeMatchTab.value = 'upload'
  matchType.value = 1 // 默认选择第一种匹配方式
  fileList.value = []
  fileSelected.value = false
  uploadedFile.value = null
  matchProgress.value = 0
  matchResult.value = { total: 0, matched: 0, unmatched: 0 }
  matchResultFile.value = null
  
  if (matchProgressInterval.value) {
    clearInterval(matchProgressInterval.value)
    matchProgressInterval.value = null
  }
  
  // 加载匹配历史记录
  loadMatchRecords();
}

const handleMatchTypeChange = (value) => {
  matchType.value = value
  // 重置文件选择状态，因为不同匹配类型的模板不同
  fileList.value = []
  fileSelected.value = false
  uploadedFile.value = null
}

const uploadFile = async (options) => {
  try {
    const { file } = options
    
    // 记录上传的文件对象，后续匹配时使用
    uploadedFile.value = file
    
    // 在这里不立即上传文件，而是等用户点击"开始匹配"按钮时再上传
    if (getCurrentLanguage() === 'zh') {
      ElMessage.success('文件已选择，请点击"开始匹配"开始处理')
    } else {
      ElMessage.success('File selected, please click "Start Match" to start processing')
    }
    
    // 标记文件已选择
    fileSelected.value = true
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('文件选择处理失败，请重新选择')
    } else {
      ElMessage.error('Failed to handle file selection, please try again')
    }
    
    // 重置文件选择状态
    fileList.value = []
    fileSelected.value = false
    uploadedFile.value = null
  }
}

const beforeUpload = (file) => {
  // 验证文件类型
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                 file.type === 'application/vnd.ms-excel' ||
                 file.name.endsWith('.xlsx') || 
                 file.name.endsWith('.xls')
                 
  if (!isExcel) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('只能上传Excel文件!')
    } else {
      ElMessage.error('Only Excel files are allowed!')
    }
    return false
  }
  
  // 验证文件大小
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('文件大小不能超过10MB!')
    } else {
      ElMessage.error('File size cannot exceed 10MB!')
    }
    return false
  }
  
  return true
}

const handleFileChange = (file, uploadFileList) => {
  // 更新文件列表
  fileList.value = uploadFileList
  
  // 只有当文件状态为success或ready时才允许进行匹配
  if (file.status === 'ready' || file.status === 'success') {
    fileSelected.value = true
    uploadedFile.value = file.raw
    
    // 重置匹配结果
    matchResult.value = { total: 0, matched: 0, unmatched: 0 }
    matchResultFile.value = null
  } else {
    fileSelected.value = false
    uploadedFile.value = null
  }
}

const handleExceed = (files) => {
  if (getCurrentLanguage() === 'zh') {
    ElMessage.warning(`当前限制选择1个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.value.length} 个文件`)
  } else {
    ElMessage.warning(`Only 1 file can be selected, you have selected ${files.length} files, total ${files.length + fileList.value.length} files`)
  }
}

const startMatch = async () => {
  if (!uploadedFile.value) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('请先选择要匹配的Excel文件')
    } else {
      ElMessage.error('Please select an Excel file to match')
    }
    return
  }
  
  try {
    matchLoading.value = true
    matchProgress.value = 0
    
    // 创建FormData，用于文件上传
    const formData = new FormData()
    formData.append('file', uploadedFile.value)
    formData.append('matchType', matchType.value)
    
    // 根据不同的匹配类型显示相应的提示信息
    let matchTypeText = getMatchTypeText(matchType.value);

    if (getCurrentLanguage() === 'zh') {
      ElMessage.info(`正在进行${matchTypeText}，请稍候...`)
    } else {
      ElMessage.info(`Matching ${matchTypeText}, please wait...`)
    }
    
    // 创建模拟进度更新的定时器
    matchProgressInterval.value = setInterval(() => {
      if (matchProgress.value < 90) {
        matchProgress.value += Math.floor(Math.random() * 5) + 1
      }
    }, 500)
    
    // 调用匹配API
    const response = await matchFacebookData(formData)
    
    // 清除定时器
    clearInterval(matchProgressInterval.value)
    matchProgressInterval.value = null
    
    if (response && response.code === 200) {
      // 设置进度为100%
      matchProgress.value = 100
      
      // 更新匹配结果
      matchResult.value = {
        total: response.data.total || 0,
        matched: response.data.matched || 0,
        unmatched: response.data.total - response.data.matched || 0
      }
      
      // 保存匹配结果文件的URL
      matchResultFile.value = response.data.fileUrl || null
      
      // 重新加载匹配历史记录
      loadMatchRecords();

      if (getCurrentLanguage() === 'zh') {
        ElMessage.success('匹配完成！')
      } else {
        ElMessage.success('Match complete!');
      }
    } else {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error(response?.msg || '匹配失败，请重试')
      } else {
        ElMessage.error('Match failed, please try again')
      }
      matchProgress.value = 0
    }
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('匹配处理失败，请重试')
    } else {
      ElMessage.error('Match processing failed, please try again')
    }
    matchProgress.value = 0
    
    // 清除定时器
    if (matchProgressInterval.value) {
      clearInterval(matchProgressInterval.value)
      matchProgressInterval.value = null
    }
  } finally {
    matchLoading.value = false
  }
}

const downloadMatchResult = () => {
  if (!matchResultFile.value) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('没有可下载的匹配结果');
    } else {
      ElMessage.error('No match result to download');
    }
    return;
  }
  
  try {
    // 确保url是有效的
    const fileUrl = matchResultFile.value.startsWith('/') 
      ? `${window.location.origin}/api${matchResultFile.value}` 
      : matchResultFile.value;

    if (getCurrentLanguage() === 'zh') {
      ElMessage.info('正在准备下载结果文件，请稍候...');
    } else {
      ElMessage.info('Preparing to download result file, please wait...');
    }
    
    // 使用XMLHttpRequest替代fetch
    const xhr = new XMLHttpRequest();
    xhr.open('GET', fileUrl, true);
    xhr.responseType = 'blob';
    xhr.withCredentials = true; // 确保发送认证信息
    
    // 从localStorage获取token并添加到请求头
    const token = localStorage.getItem('token');
    if (token) {
      xhr.setRequestHeader('Authorization', `Bearer ${token}`);
    }
    
    xhr.onload = function() {
      if (xhr.status === 200) {
        // 获取文件名
        let filename = '匹配结果.xlsx';
        const disposition = xhr.getResponseHeader('content-disposition');
        if (disposition && disposition.indexOf('filename=') !== -1) {
          const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
          const matches = filenameRegex.exec(disposition);
          if (matches != null && matches[1]) {
            filename = matches[1].replace(/['"]/g, '');
          }
        }
        
        // 创建blob链接并下载
        const blob = new Blob([xhr.response], { 
          type: xhr.getResponseHeader('content-type') || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        
        // 清理
        setTimeout(() => {
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
        }, 100);

        if (getCurrentLanguage() === 'zh') {
          ElMessage.success('下载成功');
        } else {
          ElMessage.success('Download successful');
        }
      } else {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error(`下载失败: ${xhr.status} ${xhr.statusText}`);
        } else {
          ElMessage.error(`Download failed`);
        }
      }
    };
    
    xhr.onerror = function() {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('下载失败，网络连接错误');
      } else {
        ElMessage.error('Download failed, network connection error');
      }
    };
    
    xhr.send();
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('下载匹配结果失败，请重试');
    } else {
      ElMessage.error('Failed to download match result, please try again')
    }
  }
}

// 打开匹配对话框
const openMatchDialog = () => {
  matchDialogVisible.value = true;
  // 切换到上传标签页
  activeMatchTab.value = 'upload';
  // 加载匹配历史记录
  loadMatchRecords();
};

// 关闭匹配对话框
const closeMatchDialog = () => {
  matchDialogVisible.value = false;
  // 重置相关状态
  matchProgress.value = 0;
  matchResult.value = { total: 0, matched: 0, unmatched: 0 };
  matchResultFile.value = null;
  fileList.value = [];
  fileSelected.value = false;
  uploadedFile.value = null;

  // 清除进度查询定时器
  if (matchProgressInterval.value) {
    clearInterval(matchProgressInterval.value);
    matchProgressInterval.value = null;
  }
};

// 文件移除处理
const handleFileRemove = (file, uploadFileList) => {
  fileList.value = uploadFileList;
  fileSelected.value = uploadFileList.length > 0;
  uploadedFile.value = null;
};

// 下载匹配结果
const downloadResult = () => {
  if (!matchResultFile.value) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('没有可下载的结果文件');
    } else {
      ElMessage.error('No result file to download');
    }
    return;
  }

  try {
    // 构建下载链接
    const downloadUrl = `/api/facebook/download-result?filename=${encodeURIComponent(matchResultFile.value)}`;

    if (getCurrentLanguage() === 'zh') {
      ElMessage.info('准备下载文件，请稍候...');
    } else {
      ElMessage.info('Preparing to download file, please wait...');
    }

    // 创建隐藏的下载链接
    const link = document.createElement('a');
    link.href = downloadUrl;
    link.download = matchResultFile.value;
    link.style.display = 'none';

    // 添加认证头
    const token = localStorage.getItem('token');
    if (token) {
      link.setAttribute('data-token', token);
    }

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    if (getCurrentLanguage() === 'zh') {
      ElMessage.success('文件下载开始');
    } else {
      ElMessage.success('File download started');
    }
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('下载失败，请重试');
    } else {
      ElMessage.error('Download failed, please try again');
    }
  }
};

const downloadTemplate = () => {
  try {
    // 根据匹配类型设置不同的请求参数
    let templateType = '';
    
    // 设置请求参数
    switch(matchType.value) {
      case 1:
        templateType = 'company_name_to_email';
        break;
      case 2:
        templateType = 'company_name_to_phone';
        break;
      case 3:
        templateType = 'name_email_to_phone';
        break;
      case 4:
        templateType = 'phone_name_to_email';
        break;
      default:
        templateType = 'default';
    }
    
    // 构建下载链接，使用完整的API路径
    const downloadUrl = `/api/facebook/download-template?type=${templateType}`;

    if (getCurrentLanguage() === 'zh') {
      ElMessage.info('正在准备下载模板文件，请稍候...');
    } else {
      ElMessage.info('Preparing to download template file, please wait...');
    }
    
    // 使用XMLHttpRequest进行文件下载
    const xhr = new XMLHttpRequest();
    xhr.open('GET', downloadUrl, true);
    xhr.responseType = 'blob';
    xhr.withCredentials = true; // 确保发送认证信息
    
    // 从localStorage获取token并添加到请求头
    const token = localStorage.getItem('token');
    if (token) {
      xhr.setRequestHeader('Authorization', `Bearer ${token}`);
    }
    
    xhr.onload = function() {
      if (xhr.status === 200) {
        // 获取文件名
        let filename = `匹配模板_${templateType}.xlsx`;
        const disposition = xhr.getResponseHeader('content-disposition');
        if (disposition) {
          // 优先解析 filename* (RFC 5987)
          let matchStar = /filename\*=(?:UTF-8''|'')?([^;\n]*)/i.exec(disposition);
          let matchPlain = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/i.exec(disposition);
          let raw = '';
          if (matchStar && matchStar[1]) {
            raw = matchStar[1];
          } else if (matchPlain && matchPlain[1]) {
            raw = matchPlain[1].replace(/['"]/g, '');
          }
          if (raw) {
            // 去掉 UTF-8'' 前缀
            if (raw.startsWith("UTF-8''")) raw = raw.substring(7);
            // 将加号视为空格（有些服务端按表单方式编码）
            raw = raw.replace(/\+/g, ' ');
            // 尝试解码百分号编码
            try {
              filename = decodeURIComponent(raw);
            } catch (e1) {
              try {
                filename = decodeURI(raw);
              } catch (e2) {
                // 保留原值
                filename = raw;
              }
            }
          }
        }
        
        // 创建blob链接并下载
        const blob = new Blob([xhr.response], { 
          type: xhr.getResponseHeader('content-type') || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        
        // 清理
        setTimeout(() => {
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
        }, 100);

        if (getCurrentLanguage() === 'zh'){
          ElMessage.success('模板文件下载成功');
        } else {
          ElMessage.success('Template file download successful');
        }
      } else {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error(`下载失败: ${xhr.status} ${xhr.statusText}`);
        } else {
          ElMessage.error(`Download failed`);
        }
      }
    };
    
    xhr.onerror = function() {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('下载失败，网络连接错误');
      } else {
        ElMessage.error('Download failed, network connection error');
      }
    };
    
    xhr.send();
  } catch (error) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('下载模板文件失败，请联系客服');
    } else {
      ElMessage.error('Failed to download template file, please contact customer service')
    }
  }
}

// 修改生命周期钩子的使用方式
// 确保在组件销毁前清除定时器
onMounted(() => {
  // 现有的初始化代码
  initializeLocationData();

  // 添加ES搜索相关翻译
  addTranslation('facebook.filter.es.results', {
    zh: '搜索结果',
    en: 'Search Results'
  });

  addTranslation('facebook.filter.loading', {
    zh: '搜索中...',
    en: 'Searching...'
  });
  
  addTranslation('facebook.filter.selected.custom', {
    zh: '已选择的自定义项',
    en: 'Selected Custom Items'
  });

  // 延迟验证筛选数据，确保数据加载完成
  setTimeout(() => {
    verifyFilterData();
  }, 1000);
});

// 在组件卸载时清除定时器
onBeforeUnmount(() => {
  if (matchProgressInterval.value) {
    clearInterval(matchProgressInterval.value)
    matchProgressInterval.value = null
  }
});

// 注意：在 <script setup> 中，所有顶级变量和函数都会自动暴露给模板
// 不需要显式的 return 语句

// 存储ES查询结果
const esCurrentLocations = ref([])
const esHometowns = ref([])
const esWorkplaces = ref([])
const esSearchLoading = ref({
  currentLocation: false,
  hometown: false,
  workplace: false
})

// 处理当前所在地搜索
const handleCurrentLocationSearch = debounce(async (val) => {
  if (!val || val.length < 2) {
    esCurrentLocations.value = []
    return
  }
  
  try {
    esSearchLoading.value.currentLocation = true
    const response = await searchCurrentLocationsFromES(val)
    if (response && response.code === 200 && response.data) {
      // 过滤掉已经存在于静态列表中的城市和已选中的城市
      const staticLocations = predefinedCurrentLocations.map(city => city.original)
      const selectedLocations = state.filters.currentLocations || []
      esCurrentLocations.value = response.data.filter(location => 
        !staticLocations.includes(location) && 
        !selectedLocations.includes(location)
      )
    } else {
      esCurrentLocations.value = []
    }
  } catch (error) {
    esCurrentLocations.value = []
  } finally {
    esSearchLoading.value.currentLocation = false
  }
}, 500)

// 处理家乡搜索
const handleHometownSearch = debounce(async (val) => {
  if (!val || val.length < 2) {
    esHometowns.value = []
    return
  }
  
  try {
    esSearchLoading.value.hometown = true
    const response = await searchHometownsFromES(val)
    if (response && response.code === 200 && response.data) {
      // 过滤掉已经存在于静态列表中的城市和已选中的城市
      const staticLocations = predefinedHometowns.map(city => city.original)
      const selectedLocations = state.filters.hometowns || []
      esHometowns.value = response.data.filter(location => 
        !staticLocations.includes(location) && 
        !selectedLocations.includes(location)
      )
    } else {
      esHometowns.value = []
    }
  } catch (error) {
    esHometowns.value = []
  } finally {
    esSearchLoading.value.hometown = false
  }
}, 500)

// 处理工作地点搜索
const handleWorkplaceSearch = debounce(async (val) => {
  if (!val || val.length < 2) {
    esWorkplaces.value = []
    return
  }
  
  try {
    esSearchLoading.value.workplace = true
    const response = await searchWorkplacesFromES(val)
    if (response && response.code === 200 && response.data) {
      // 过滤掉已经存在于静态列表中的工作地点和已选中的工作地点
      const staticWorkplaces = predefinedWorkplaces.map(workplace => workplace.original)
      const selectedWorkplaces = state.filters.workplaces || []
      esWorkplaces.value = response.data.filter(workplace => 
        !staticWorkplaces.includes(workplace) && 
        !selectedWorkplaces.includes(workplace)
      )
    } else {
      esWorkplaces.value = []
    }
  } catch (error) {
    esWorkplaces.value = []
  } finally {
    esSearchLoading.value.workplace = false
  }
}, 500)

// 从已选择的城市中找出不在预定义列表中的项（来自ES搜索结果）
const selectedCustomCurrentLocations = computed(() => {
  if (!state.filters.currentLocations || state.filters.currentLocations.length === 0) {
    return [];
  }
  
  const predefinedOriginals = predefinedCurrentLocations.map(item => item.original);
  return state.filters.currentLocations.filter(location => !predefinedOriginals.includes(location));
});

// 从已选择的家乡中找出不在预定义列表中的项（来自ES搜索结果）
const selectedCustomHometowns = computed(() => {
  if (!state.filters.hometowns || state.filters.hometowns.length === 0) {
    return [];
  }
  
  const predefinedOriginals = predefinedHometowns.map(item => item.original);
  return state.filters.hometowns.filter(hometown => !predefinedOriginals.includes(hometown));
});

// 从已选择的工作地点中找出不在预定义列表中的项（来自ES搜索结果）
const selectedCustomWorkplaces = computed(() => {
  if (!state.filters.workplaces || state.filters.workplaces.length === 0) {
    return [];
  }
  
  const predefinedOriginals = predefinedWorkplaces.map(item => item.original);
  return state.filters.workplaces.filter(workplace => !predefinedOriginals.includes(workplace));
});
</script>

<style scoped>
/* 主容器样式 */
.facebook-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f0f2f5; /* Facebook 背景色 */
  overflow: hidden;
}

/* 主内容区样式 */
.main-container {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 内容区样式 */
.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 16px;
  overflow-y: auto; /* 内容区域可滚动 */
}

/* 搜索容器 */
.search-container {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 16px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.search-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
}

.search-box-container {
  max-width: 360px;
  margin: 0 auto;
}

.search-input {
  width: 100%;
}

:deep(.el-input__inner) {
  height: 40px;
  line-height: 40px;
  border-radius: 4px;
  font-size: 16px;
  text-align: center;
}

/* 主要布局 */
.facebook-main {
  display: flex;
  gap: 20px; /* 筛选器与内容区之间的间隔 */
  flex: 1;
}

/* 筛选侧边栏样式 */
.filter-sidebar-container {
  width: 280px;
  flex-shrink: 0; /* 防止侧边栏宽度被压缩 */
  position: relative; /* 为固定定位做准备 */
}

/* 匹配对话框样式 */
.match-dialog-content {
  padding: 20px 0;
}

.match-info {
  margin-bottom: 20px;
}

.match-info p {
  margin-bottom: 10px;
  font-size: 14px;
}

.match-type-select {
  margin-bottom: 20px;
}

.match-type-select p {
  font-weight: bold;
  margin-bottom: 10px;
}

.match-type-select .el-radio-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.file-upload-container {
  margin-bottom: 20px;
}

.file-upload-container p {
  font-weight: bold;
  margin-bottom: 10px;
}

.template-download {
  margin-bottom: 20px;
  text-align: right;
}

.match-progress {
  margin-bottom: 20px;
}

.match-progress p {
  font-weight: bold;
  margin-bottom: 10px;
}

.match-result {
  margin-top: 20px;
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
}

.match-result p {
  font-weight: bold;
  margin-bottom: 10px;
}

.result-stats {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.result-stats p {
  margin: 0;
  font-weight: normal;
}

.match-success {
  color: #67c23a;
  font-weight: bold;
}



/* 自定义上传样式 */
:deep(.el-upload-dragger) {
  width: 100%;
  height: 180px;
}

:deep(.el-icon--upload) {
  font-size: 48px;
  margin-bottom: 16px;
  color: #409eff;
}

:deep(.el-upload__text) {
  font-size: 16px;
}

:deep(.el-upload__text em) {
  color: #409eff;
  font-style: normal;
  text-decoration: underline;
}

:deep(.el-upload__tip) {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}
.filter-sidebar {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 15px;
  position: sticky; /* 使筛选器在滚动时保持可见 */
  top: 20px; /* 距离顶部的距离 */
  max-height: calc(100vh - 100px); /* 最大高度，确保在小屏幕上可以滚动 */
  overflow-y: auto; /* 内容溢出时显示滚动条 */
}

/* 重置筛选器按钮 */
.reset-filter-container {
  margin-bottom: 15px;
  text-align: center;
}

.reset-filter-btn {
  width: 100%;
}

/* 筛选组样式 */
.filter-group {
  margin-bottom: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden; /* 防止内容溢出 */
}

.filter-group.expanded {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #f5f7fa;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
}

.filter-content {
  padding: 15px;
  max-height: 250px; /* 限制最大高度 */
  overflow-y: auto; /* 内容溢出时显示滚动条 */
}

/* 筛选器内搜索框 */
.filter-search {
  margin-bottom: 10px;
}

.filter-search .el-input__inner {
  height: 32px;
  line-height: 32px;
  font-size: 12px;
}

.checkbox-list {
  margin-top: 8px;
  display: flex;
  flex-direction: column;
  gap: 4px; /* 减小间距从8px到4px */
  max-height: none;
  overflow: visible;
}

.filter-checkbox {
  margin-left: 0;
  font-size: 13px;
}

.salary-range-text {
  margin-top: 8px;
  text-align: center;
  color: #606266;
  font-size: 13px;
}

/* 数据内容区 */
.data-content {
  flex: 1;
  min-width: 0;
  background-color: transparent;
  display: flex;
  flex-direction: column;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  width: 100%;
  background-color: #fff;
  padding: 15px 20px;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

/* 添加符合条件数量样式 */
.matched-count {
  display: flex;
  align-items: center;
  font-size: 16px;
  color: #606266;
}

.matched-count-number {
  font-weight: bold;
  color: #409eff;
  margin: 0 2px;
}

.export-container {
  display: inline-block;
  text-align: right;
}

.export-btn {
  background-color: #1877f2; /* Facebook 蓝色 */
  color: white;
  border: none;
}

.export-btn:hover {
  background-color: #166fe5; /* 稍深的蓝色 */
}

/* 联系人卡片列表 */
.contact-card-list {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 20px;
}

.contact-card {
  background-color: #ffffff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  margin-bottom: 16px;
  border: 1px solid #ebeef5;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 16px 16px 24px; /* 增加左侧内边距，与卡片内容区域保持一致 */
  border-bottom: 1px solid #f0f0f0;
}

.avatar-name-container {
  display: flex;
  align-items: center;
  padding-left: 10px; /* 为头像名称容器添加左边距 */
}

.avatar-container {
  margin-right: 12px;
}

.contact-avatar {
  border: none;
}

.header-info {
  display: flex;
  flex-direction: column;
}

.contact-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.contact-location {
  font-size: 14px;
  color: #555;
  display: flex;
  align-items: center;
}

.country-flag {
  width: 16px;
  height: 11px;
  margin-right: 5px;
  object-fit: contain;
}

/* 详情按钮样式 */
.detail-button-container {
  margin-left: auto;
  display: flex;
  align-items: flex-start;
  margin-top: 55px; /* 根据第二张图调整顶部外边距 */
}

.detail-btn {
  background-color: #ecf5ff;
  border: none;
  color: #409EFF;
  font-size: 15px;
  font-weight: normal;
  padding: 8px 16px;
  border-radius: 4px;
  height: auto;
  line-height: 1;
}

.detail-btn:hover {
  background-color: #d9ecff;
}

/* 卡片内容区域 */
.card-content {
  padding: 16px 16px 16px 24px; /* 增加左侧内边距 */
}

/* 信息行样式 */
.info-row {
  display: flex;
  margin-bottom: 10px;
  line-height: 1.5;
  padding-left: 10px; /* 为信息行添加左边距 */
}

.info-label {
  font-size: 14px;
  color: #666;
  min-width: 70px;
  margin-right: 12px; /* 增加标签和值之间的间距 */
}

.info-value {
  font-size: 14px;
  color: #333;
  flex: 1;
}

.contact-method {
  color: #409EFF;
}

/* 基础信息和详细信息区域 */
.basic-info, .detailed-info {
  display: flex;
  flex-direction: column;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 25px;
  margin-bottom: 25px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.pagination-container :deep(.el-pagination) {
  font-weight: normal;
  justify-content: center;
  width: 100%;
}

.pagination-container :deep(.el-pagination .el-pagination__total) {
  font-weight: bold;
}

.pagination-container :deep(.el-pagination .el-pagination__sizes) {
  margin-right: 15px;
}

/* 无数据样式 */
.no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 0;
  color: #65676b;
}

.no-data i {
  font-size: 48px;
  margin-bottom: 16px;
}

.no-data p {
  font-size: 16px;
}

/* 添加到线索弹窗 */
.add-to-leads-form {
  padding: 0 16px;
}

.dialog-footer {
  margin-top: 16px;
}

/* 自定义滚动条 */
.filter-sidebar::-webkit-scrollbar,
.contact-card-list::-webkit-scrollbar {
  width: 6px;
}

.filter-sidebar::-webkit-scrollbar-track,
.contact-card-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.filter-sidebar::-webkit-scrollbar-thumb,
.contact-card-list::-webkit-scrollbar-thumb {
  background: #c2c2c2;
  border-radius: 3px;
}

.filter-sidebar::-webkit-scrollbar-thumb:hover,
.contact-card-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式调整 */
@media screen and (max-width: 1200px) {
  .facebook-main {
    flex-direction: column;
  }
  
  .filter-sidebar-container {
    width: 100%;
    margin-right: 0;
    margin-bottom: 16px;
    max-height: 300px;
  }
}

@media screen and (max-width: 768px) {
  .search-box-container .el-row {
    display: flex;
    flex-direction: column;
  }
  
  .search-box-container .el-col {
    width: 100%;
    margin-bottom: 8px;
  }
  
  .content {
    padding: 12px;
  }
  
  .contact-header {
    flex-direction: column;
  }
  
  .contact-name-section {
    margin-bottom: 12px;
  }
}

/* 日期选择器样式覆盖 */
:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-date-editor--daterange) {
  width: 100%;
}

/* 主题色调整 */
:deep(.el-button--primary) {
  background-color: #1877f2;
  border-color: #1877f2;
}

:deep(.el-button--primary:hover) {
  background-color: #166fe5;
  border-color: #166fe5;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner),
:deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #1877f2;
  border-color: #1877f2;
}

:deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
  background-color: #1877f2;
}

:deep(.el-pagination.is-background .el-pager li:not(.disabled).active) {
  background-color: #1877f2;
}

/* 新增样式 */
.filter-search {
  margin-bottom: 16px;
}

.checkbox-list {
  margin-top: 12px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.filter-checkbox {
  color: #409eff !important;
  margin-left: 0;
}

.dialog-footer {
  margin-top: 16px;
}

.radio-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-top: 10px;
}

.radio-list .el-radio {
  margin-right: 0;
  margin-left: 0;
}

.radio-option {
  padding: 8px 0;
  cursor: pointer;
}

.radio-full-width {
  width: 100%;
  margin-right: 0;
}

.checkbox-option {
  padding: 4px 0; /* 从10px减小到4px */
  margin-bottom: 6px;
  cursor: pointer;
}

.checkbox-list {
  margin-top: 10px;
}

.small-text-input :deep(.el-input__inner) {
  font-size: 12px;
}

.hot-locations {
  margin-top: 12px;
  margin-bottom: 12px;
}

.section-divider {
  margin: 12px 0;
  border-bottom: 1px solid #ebeef5; /* 恢复分隔线 */
  padding-bottom: 8px;
  text-align: left; /* 改为左对齐 */
  padding-right: 0; /* 移除右侧内边距 */
}

.section-title {
  font-size: 15px; /* 调整字体大小 */
  font-weight: 500; /* 调整字重 */
  color: #606266; /* 恢复原来的颜色 */
  margin-bottom: 8px;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.location-tag {
  cursor: pointer;
  margin-right: 0;
}

.location-tag.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}



/* 为复选框增加间距和大小 */
:deep(.el-checkbox) {
  display: block;
  margin-right: 0;
  margin-bottom: 4px; /* 从8px减小到4px */
  font-size: 14px;
  height: 24px; /* 添加固定高度使选项更紧凑 */
  line-height: 24px; /* 确保垂直居中对齐 */
}

:deep(.el-checkbox__inner) {
  width: 20px;
  height: 20px;
  border-radius: 4px;
}

:deep(.el-checkbox__inner::after) {
  width: 7px;
  height: 10px;
  border-width: 2px;
  top: 2px;
  left: 6px;
  transform-origin: center;
}

:deep(.el-checkbox__label) {
  font-size: 15px;
  padding-left: 12px;
}

/* 调整筛选面板内复选框的样式 */
.filter-group .el-checkbox {
  margin-left: 0;
}

/* 确保全选复选框与其他选项有明显间隔 */
.filter-group .checkbox-option:first-child {
  margin-bottom: 12px;
  border-bottom: 1px dashed #ebeef5;
}

/* 为全选项添加特殊样式，与其他选项区分 */
.select-all {
  margin-bottom: 8px; /* 从12px减小到8px */
  padding-bottom: 8px; /* 从10px减小到8px */
  border-bottom: 1px dashed #EBEEF5;
}

/* 添加提示文本样式 */
.filter-hint {
  font-size: 12px;
  color: #909399;
  margin-left: 8px;
  font-weight: normal;
}

/* 新增样式 - 详情按钮容器 */
.detail-button-container {
  margin-left: auto;
}

/* 修改详情按钮样式 */
.detail-btn {
  font-size: 15px; /* 增大字体 */
  padding: 8px 16px; /* 增大内边距 */
}

/* 收起按钮容器 */
.collapse-btn-container {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}

/* 加载状态容器 */
.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #666;
  font-size: 14px;
}

.loading-text {
  margin-left: 8px;
}

/* 联系人卡片样式 */
.contact-card {
  background-color: #ffffff;
  margin-bottom: 12px;
  border-bottom: 1px solid #e4e6eb;
}

/* 卡片头部区域 */
.card-header {
  display: flex;
  align-items: center;
  padding: 16px;
}

.contact-avatar {
  margin-right: 12px;
}

.contact-info {
  flex: 1;
}

.contact-name {
  font-size: 16px;
  font-weight: 500;
  color: #050505;
  display: flex;
  align-items: center;
}

.flag-icon {
  width: 16px;
  height: 12px;
  margin-left: 6px;
}

.contact-location {
  font-size: 14px;
  color: #65676b;
  margin-top: 2px;
}

/* 骨架屏加载样式 */
.skeleton-loading {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 10px 0;
}

.skeleton-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  height: 120px;
  border: 1px solid #ebeef5;
}

.skeleton-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.skeleton-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 50%, #f2f2f2 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
  margin-right: 12px;
}

.skeleton-title {
  height: 20px;
  width: 150px;
  border-radius: 4px;
  background: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 50%, #f2f2f2 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

.skeleton-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.skeleton-line {
  height: 14px;
  width: 100%;
  border-radius: 4px;
  background: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 50%, #f2f2f2 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

.skeleton-line:nth-child(2) {
  width: 80%;
}

.skeleton-line:nth-child(3) {
  width: 60%;
}

@keyframes shimmer {
  0% {
    background-position: -200% 0;
  }
  100% {
    background-position: 200% 0;
  }
}

/* 轮廓骨架屏动效 */
@keyframes shimmer {
  0% {
    background-position: -200% 0;
  }
  100% {
    background-position: 200% 0;
  }
}

/* 导出对话框样式 */
.export-dialog-content {
  padding: 10px 0;
}

/* Facebook链接样式 */
.facebook-link {
  color: #1877f2;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  transition: color 0.2s;
}

.facebook-link:hover {
  color: #166fe5;
  text-decoration: underline;
}

.external-link-icon {
  margin-left: 4px;
  font-size: 14px;
}

.copy-link-btn {
  margin-left: 8px;
  padding: 0;
  height: auto;
  font-size: 12px;
  color: #909399;
}

.copy-link-btn:hover {
  color: #409EFF;
}

.export-info {
  margin-bottom: 20px;
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
}

.export-highlight {
  font-weight: bold;
  color: #409eff;
  margin: 0 5px;
}

.export-input {
  margin-bottom: 15px;
}

.export-input p {
  margin-bottom: 10px;
}

.export-warnings {
  margin-top: 15px;
}

.export-warning {
  color: #f56c6c;
  font-size: 13px;
  margin: 5px 0;
  display: flex;
  align-items: center;
}

.export-warning i {
  margin-right: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.export-note {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

.export-limit-notice {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

/* 匹配对话框样式 */
.match-dialog-content {
  padding: 20px 0;
}

.match-info {
  margin-bottom: 20px;
}

.match-info p {
  margin-bottom: 10px;
  font-size: 14px;
}

.match-type-select {
  margin-bottom: 20px;
}

.match-type-select p {
  font-weight: bold;
  margin-bottom: 10px;
}

.match-type-select .el-radio-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.file-upload-container {
  margin-bottom: 20px;
}

.file-upload-container p {
  font-weight: bold;
  margin-bottom: 10px;
}

.template-download {
  margin-bottom: 20px;
  text-align: right;
}

.match-progress {
  margin-bottom: 20px;
}

.match-progress p {
  font-weight: bold;
  margin-bottom: 10px;
}

.match-result {
  margin-top: 20px;
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
}

.match-result p {
  font-weight: bold;
  margin-bottom: 10px;
}

.result-stats {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.result-stats p {
  margin: 0;
  font-weight: normal;
}

.match-success {
  color: #67c23a;
  font-weight: bold;
}

.match-fail {
  color: #f56c6c;
  font-weight: bold;
}

.match-btn {
  background-color: #409eff;
  color: white;
  border: none;
}

.match-btn:hover {
  background-color: #3a8ee6;
}

/* 自定义上传样式 */
:deep(.el-upload-dragger) {
  width: 100%;
  height: 180px;
}

:deep(.el-icon--upload) {
  font-size: 48px;
  margin-bottom: 16px;
  color: #409eff;
}

:deep(.el-upload__text) {
  font-size: 16px;
}

:deep(.el-upload__text em) {
  color: #409eff;
  font-style: normal;
  text-decoration: underline;
}

:deep(.el-upload__tip) {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

/* 匹配对话框样式 */
.match-dialog-content {
  padding: 20px 0;
}

.match-history {
  padding: 10px;
}

.match-history .pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* ES查询相关样式 */
.filter-search {
  margin-bottom: 10px;
  position: relative;
}

.filter-search.is-loading .el-input__inner {
  padding-right: 95px; /* 为加载状态文本留出空间 */
}

.filter-search-loading {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
  color: #409eff;
  display: flex;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 0 5px;
  border-radius: 3px;
  z-index: 2;
}

.filter-search-loading i {
  margin-right: 5px;
  font-size: 14px;
  animation: rotating 1s linear infinite;
}

/* ES查询结果分隔线 */
.es-result-divider {
  padding: 8px 0;
  margin: 8px 0;
  font-size: 13px;
  color: #409eff;
  font-weight: 500;
  border-top: 1px dashed #e0e0e0;
  border-bottom: 1px dashed #e0e0e0;
  text-align: center;
  background-color: #f5f7fa;
  border-radius: 3px;
}

/* 已选择的自定义项容器 */
.es-selected-items {
  margin-bottom: 12px;
  padding-bottom: 8px;
  background-color: #f0faff;
  border-radius: 4px;
  padding: 5px;
}

.es-selected-items .es-result-divider {
  background-color: #ecf5ff;
  color: #409eff;
  font-weight: bold;
  margin-top: 0;
}

@keyframes rotating {
  from {
    transform: rotate(0);
  }
  to {
    transform: rotate(360deg);
  }
}
</style> 
